How to remove time portion of date in C# in DateTime object only?
Use the Date property:
var dateAndTime = DateTime.Now;
var date = dateAndTime.Date;
The date
variable will contain the date, the time part will be 00:00:00
.
Removing Time from DateTime
You'll need to tell it a format specifier;
Console.WriteLine(p.DateOfBirth.ToString("..."));
where "..."
is your choice; "d"
maybe (short date). See standard and custom formats.
Remove time from time and date
You need to convert your date into a DateTime
object first. See examples here if your string is in a different or custom format.
openDate = !string.IsNullOrEmpty(node.ChildNodes[f].Attributes["ows_PMO_x0020_Origination_x0020_Date"].Value)? node.ChildNodes[f].Attributes["ows_PMO_x0020_Origination_x0020_Date"].Value: "" ;
//openDate is a string at this point. You'll need to convert it to a datetime object first, for the following line to work:
var dtObject = DateTime.Parse(openDate);
//Format the newly created datetime object
openDate = String.Format("{0:MM/dd/yyyy}", dtObject);
removing time from datetime in c# and retaining datetime format
The Date
property of the DateTime
struct will give you a date but it will always have a time component that represents midnight ("00:00:00"). If you're starting with a string, you might be able to work with something like this:
DateTime d = DateTime.Parse("2/27/2013 4:18:53 PM").Date; // 2/27/2013 12:00:00 AM
Just make sure you perform your comparison on DateTime
objects (i.e. omit all usages of ToString()
).
Alternatively, you can format your date in the "sortable" time format:
string d = DateTime.Parse("2/27/2013 4:18:53 PM").ToString("s");
or
string d = yourDateTime.ToString("s");
For the above case d
would be 2013-02-27T16:18:53
. When sorted alphabetically, the strings will be in chronological order.
Related Topics
How to Save/Download Pdf Embedded in Web Page Without a Pdf Filename
Updating an Object from a List in C#
Return Json, But It Includes Backward Slashes "\", Which I Don't Want
How to Pass Parameter from @Url.Action to Controller Function
How to Format a Number in C# With Commas and Decimals
Most Efficient Way to Compare Two Ienumerables (Or Lists) in Linq
What Is the Correct Way to Compare Char Ignoring Case
Build Query String for System.Net.Httpclient Get
How to Format Number as Money Using Regex
Create a C# Method to Generate Auto Increment Id
Choosing the Default Value of an Enum Type Without Having to Change Values
How to Validate a Datetime in C#
Console.Writeline Does Not Show Up in Output Window
Deserialize Json String in to Multiple C# Objects
Convert Time With Milliseconds to Datetime in C#