0

I use DateTime.UtcNow.ToLongTimeString() to get the current time string.

However it behaves weird, sometimes it returns time like 3:10:00 and sometimes like 03:10:00 (leading zero). Why this happens?

I set a culture on application startup

Thread.CurrentThread.CurrentCulture = new CultureInfo(...);
Thread.CurrentThread.CurrentUICulture = new CultureInfo(...);

And the different result for the time string comes from a Task (from what I can see now). So I create a Task and .Wait() for it to finish. Inside the task the time is converted to string differently.

UPDATE

For those who are interested, here is some helpful reading I found:

Is there a way of setting culture for a whole application? All current threads and new threads?
http://msdn.microsoft.com/en-us/library/system.globalization.cultureinfo.defaultthreadcurrentculture.aspx

Community
  • 1
  • 1
net_prog
  • 9,921
  • 16
  • 55
  • 70

1 Answers1

1

However it behaves weird, sometimes it returns time like 3:10:00 and sometimes like 03:10:00 (leading zero).

You haven't said anything about where this happens - but it could certain happen if you use different cultures. Normally without the leading zero I'd expect to see an am/pm designator as well though.

If you want consistent results, always specify the same culture (e.g. CultureInfo.InvariantCulture).

Of course, if this has all been on the same system without changing culture settings, that's a different matter.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • This happens when I call `.ToLongTimeString()` from a Task, i.e. from the main thread it returns "03" and from the Task it returns "3". For the main thread I specify a culture at application startup. Seems I need to pass the main thread's culture to the task. I thought it would pick the culture automatically. – net_prog Dec 14 '12 at 07:10
  • 1
    @net_prog: No, I don't believe culture is propagated either. (I'd have expected it to be too, but I just recently learned that it *isn't* part of the `ExecutionContext`, although it probably should be.) – Jon Skeet Dec 14 '12 at 07:12