11

I'm having some trouble displaying the time in this format: HH:mm:ss. No matter what i try, i never get it in that format.

I want the time in the culture of the Netherlands which is "nl-NL".

This was one of my (although i forgot to keep the count) 1000th try:

CultureInfo ci = new CultureInfo("nl-NL");

string s = DateTime.Now.TimeOfDay.ToString("HH:mm:ss", ci);

What am i doing wrong?

abatishchev
  • 98,240
  • 88
  • 296
  • 433
Yustme
  • 6,125
  • 22
  • 75
  • 104
  • TimeSpan has a wimpy ToString() method. Changed in .NET 4.0, not for the better. Just lose "TimeofDay'. Darin got it right of course. – Hans Passant Aug 01 '10 at 12:48

3 Answers3

22
string s = DateTime.Now.ToString("HH:mm:ss");
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
9

You need to use the TimeZoneInfo class, here's how to show the current time in the Eastern Standard Time time zone in HH:mm:ss format:

var timeZone = TimeZoneInfo.FindSystemTimeZoneById("Eastern Standard Time");
string s = TimeZoneInfo.ConvertTime(DateTime.Now, timeZone).ToString("HH:mm:ss");

To find all the timezones available, you can use

TimeZoneInfo.GetSystemTimeZones();

Looking through the returned value from the above, the Id for the time zone you need (Amsterdam I assume) is called W. Europe Standard Time:

var timeZone = TimeZoneInfo.FindSystemTimeZoneById("W. Europe Standard Time");
string s = TimeZoneInfo.ConvertTime(DateTime.Now, timeZone).ToString("HH:mm:ss");
theburningmonk
  • 15,701
  • 14
  • 61
  • 104
  • Thanks thebunringmonk! That did the trick. Can't believe how long i've been looking for a solution to fix this! – Yustme Aug 01 '10 at 16:53
  • @Yustme - No probs, glad I could help ;-) Globalization is not that well covered as not many of us do it, I did come across some good MSDN article on it a while back but can't seem to find the link now, will post an update if I find it again. – theburningmonk Aug 02 '10 at 11:06
1

TimeOfDay is a TimeSpan, which has only one ToString() without parameters. Use Darin's solution or a sample from MSDN documentation for TimeSpan.ToString()

Community
  • 1
  • 1
Viktor Jevdokimov
  • 1,054
  • 6
  • 13