Extract part of date from DateTime in C #

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

+53
comparison c # datetime
Oct. 12 '11 at 13:00
source share
5 answers

DateTime is a data type that is used to store both Date and Time . But it does provide properties for getting the Date Part.

You can get the Date part from the 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 
+95
Oct. 12 2018-11-12T00:
source share
โ€” -

Unable to undo the time component.

DateTime.Today same as:

 DateTime d = DateTime.Now.Date; 

If you want to display only part of the date, just do it - use ToString with the format string you need.

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

 d.ToString("D"); 
+29
12 Oct '11 at 13:01
source share

When comparing only data dates, use the Date property. So this should work for you.

 datetime1.Date == datetime2.Date 
+13
Oct 12 2018-11-12T00:
source share
  DateTime d = DateTime.Today.Date; Console.WriteLine(d.ToShortDateString()); // outputs just date 

if you want to compare dates ignoring part of the time, use the DateTime.Year and DateTime.DayOfYear properties.

code snippet

  DateTime d1 = DateTime.Today; DateTime d2 = DateTime.Today.AddDays(3); if (d1.Year < d2.Year) Console.WriteLine("d1 < d2"); else if (d1.DayOfYear < d2.DayOfYear) Console.WriteLine("d1 < d2"); 
+9
Oct. 12 '11 at 13:17
source share

you can use formatstring

 DateTime time = DateTime.Now; String format = "MMM ddd d HH:mm yyyy"; Console.WriteLine(time.ToString(format)); 
+5
Oct. 12 2018-11-12T00:
source share



All Articles