End date 24:00 (midnight)

I have a client who wants to see the midnight presented at the end of the previous day.

Example

var date = DateTime.Parse("1/27/2010 0:00"); Console.WriteLine(date.ToString(<some format>)); 

Display:

 1/26/2010 24:00 

I believe that this is valid in the ISO 8601 standard. ( See this )

Is there a way to support this in .net (without ugly string manipulation)?

+7
c # datetime
source share
2 answers

I think for dates you will need a custom formatter. See the IFormatProvider and ICustomFormatter interfaces.

This and this can also help.

+7
source share

You can customize the extension method, although using IFormatProvider as suggested by Lucero would probably be the appropriate approach. The extension method is compared with the Date property of Date , which returns the date when the time component is set to midnight. It would be like this:

 public static class Extensions { public static string ToCustomFormat(this DateTime date) { if (date.TimeOfDay < TimeSpan.FromMinutes(1)) { return date.AddDays(-1).ToString("MM/dd/yyyy") + " 24:00"; } return date.ToString("MM/dd/yyyy H:mm"); } } 

Then call it using:

 var date = DateTime.Parse("1/27/2010 0:00"); Console.WriteLine(date.ToCustomFormat()); 

EDIT: Updated for comments.

+2
source share

All Articles