Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Display current time in this format: HH:mm:ss

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?

like image 212
Yustme Avatar asked Aug 01 '10 10:08

Yustme


People also ask

How to get current time in HH mm SS format in c#?

Console. WriteLine(now. ToString("hh:mm:ss tt")); The hh specifier is the hour, using a 12-hour clock from 01 to 12, the mm is the minute, from 00 through 59, the ss is the second, from 00 through 59, and the tt is the AM/PM designator.

How do I get milliseconds in C#?

To get the milliseconds only of the current time, we use the "Millisecond" property of the DateTime class in C#. We use the "Millisecond" property with the object of DateTime class which should be initialized with the current date-time i.e. "Now".


3 Answers

string s = DateTime.Now.ToString("HH:mm:ss");
like image 51
Darin Dimitrov Avatar answered Oct 25 '22 05:10

Darin Dimitrov


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");
like image 33
theburningmonk Avatar answered Oct 25 '22 05:10

theburningmonk


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

like image 35
Viktor Jevdokimov Avatar answered Oct 25 '22 03:10

Viktor Jevdokimov