Ryan Lundy
Ryan Lundy

Reputation: 210210

DateTime formatting: Why don't ToShortTimeString and "{0:t}" display the same thing?

var todayAt2PM = new DateTime(
    DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, 14, 0, 0);
Debug.Print("{0:t}", todayAt2PM);
Debug.Print("{0}", todayAt2PM.ToString("t"));
Debug.Print("{0}", todayAt2PM.ToShortTimeString());

When I run this in C#, I get:

14:00
2:00 PM
2:00 PM

CultureInfo.CurrentCulture and CultureInfo.CurrentUICulture are both set to "en-US" on my PC. I haven't done any customizations to my regional settings; when I go to that part of Control Panel, everything indicates 12-hour time, with AM and PM.

So why does "{0:t}" print using 24-hour time?

Upvotes: 3

Views: 571

Answers (1)

Thomas Levesque
Thomas Levesque

Reputation: 292505

I think the problem is with Debug.Print rather than with the t format specifier. If you use Console.WriteLine instead of Debug.Print, it gives the expected result.

EDIT: just had a look with Reflector... Debug.Print always uses the invariant culture, not the current culture, and the time format in that culture is 24-hour

[Conditional("DEBUG")]
public static void Print(string format, params object[] args)
{
    TraceInternal.WriteLine(string.Format(CultureInfo.InvariantCulture, format, args));
}

Upvotes: 6

Related Questions