tags:

views:

248

answers:

2

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)?

+4  A: 

I guess you'll need a custom formatter for the dates. Look at the IFormatProvider and ICustomFormatter interfaces.

This and this may also help.

Lucero
Thank you, Lucero. I thought these interfaces might be useful. (+1) If this works, I'll post an example.
Mark Good
The custom formatter works with string.Format(), but ICustomFormatter.Format() never gets called when using date.ToString(new MyFormatter());
Mark Good
+2  A: 

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.

Ahmad Mageed
There are 60,000 milliseconds in that minute and this one only works with one of them (DateTime.Today representing 0:00.000 AM)
DrJokepu
@DrJokepu: I'm not sure I follow. Can you please elaborate? If the input is midnight as given by the OP the comparison should be fine. If milliseconds are included, such as `0:00:30`, the above will return the current day unless it is made to check against the `Hour` and `Minute` properties.
Ahmad Mageed
Plus 1 for the example. I think you're right about Lucero's suggestion.
Mark Good
DrJokepu is right. The fix is to replace your test "date == date.Date" by something like "date.TimeOfDay < TimeSpan.FromMinutes(1)". This will display 24:00 during the whole of the first minute of the day. Nevertheless, custom formatting is a better solution.
Joe
@Joe updated, thanks for jumping in.
Ahmad Mageed