How to Remove Time Portion of Date in C# in Datetime Object Only

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



Leave a reply



Submit