Reputation: 4303
I have a customer that wants to see midnight represented as the end of the prior 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 this is valid in the ISO 8601 standard. (see this)
Is there any way to support this in .net (without an ugly string manipulation hack)?
Upvotes: 8
Views: 4241
Reputation: 96477
You could setup an extension method, although the proper approach would probably be to use the IFormatProvider as Lucero suggested. The extension method would compare to the date's Date property, which returns the date with the time component set to midnight. It would be similar to 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 per comments.
Upvotes: 3
Reputation: 60190
I guess you'll need a custom formatter for the dates. Look at the IFormatProvider
and ICustomFormatter
interfaces.
Upvotes: 7