8

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

Mark Good
  • 4,271
  • 2
  • 31
  • 43

2 Answers2

7

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

This and this may also help.

Community
  • 1
  • 1
Lucero
  • 59,176
  • 9
  • 122
  • 152
  • Thank you, Lucero. I thought these interfaces might be useful. (+1) If this works, I'll post an example. – Mark Good Jan 28 '10 at 01:38
  • The custom formatter works with string.Format(), but ICustomFormatter.Format() never gets called when using date.ToString(new MyFormatter()); – Mark Good Jan 28 '10 at 02:25
3

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.

Community
  • 1
  • 1
Ahmad Mageed
  • 94,561
  • 19
  • 163
  • 174
  • 2
    There are 60,000 milliseconds in that minute and this one only works with one of them (DateTime.Today representing 0:00.000 AM) – Tamas Czinege Jan 27 '10 at 21:27
  • @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 Jan 27 '10 at 21:36
  • Plus 1 for the example. I think you're right about Lucero's suggestion. – Mark Good Jan 28 '10 at 01:34
  • 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 Jan 28 '10 at 08:24