Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

extract the date part from DateTime in C# [duplicate]

The line of code DateTime d = DateTime.Today; results in 10/12/2011 12:00:00 AM. How can I get only the date part.I need to ignore the time part when I compare two dates.

like image 458
Rauf Avatar asked Oct 12 '11 13:10

Rauf


People also ask

How can we get date from DateTime variable?

var testDate = startDate. AddDays(i); var testDateOnly = testDate. Date; But it returns the same {01/02/2016 AM 12:00:00} .

Is there a date data type in C#?

There is no Date DataType. However you can use DateTime.


2 Answers

DateTime is a DataType which is used to store both Date and Time. But it provides Properties to get the Date Part.

You can get the Date part from Date Property.

http://msdn.microsoft.com/en-us/library/system.datetime.date.aspx

DateTime date1 = new DateTime(2008, 6, 1, 7, 47, 0); Console.WriteLine(date1.ToString());  // Get date-only portion of date, without its time. DateTime dateOnly = date1.Date; // Display date using short date string. Console.WriteLine(dateOnly.ToString("d")); // Display date using 24-hour clock. Console.WriteLine(dateOnly.ToString("g")); Console.WriteLine(dateOnly.ToString("MM/dd/yyyy HH:mm"));    // The example displays the following output to the console: //       6/1/2008 7:47:00 AM //       6/1/2008 //       6/1/2008 12:00 AM //       06/01/2008 00:00 
like image 88
Sreekumar P Avatar answered Sep 21 '22 21:09

Sreekumar P


There is no way to "discard" the time component.

DateTime.Today is the same as:

DateTime d = DateTime.Now.Date; 

If you only want to display only the date portion, simply do that - use ToString with the format string you need.

For example, using the standard format string "D" (long date format specifier):

d.ToString("D"); 
like image 41
Oded Avatar answered Sep 22 '22 21:09

Oded