dban10
dban10

Reputation:

DateTime in C#

How would I display the current time that could be either in 24 hour format or am/pm format depending on windows setting in C#?

Upvotes: 2

Views: 461

Answers (2)

mkchandler
mkchandler

Reputation: 4758

Here is a way to do custom time in a very customizable way:

DateTime date = DateTime.Now;
string time = date.ToString("hh:mm:ss tt", CultureInfo.InvariantCulture);

The "tt" formatter is what specifies AM or PM. You customize the time even further if you want. Here's a great MSDN article that lists the custom formatters and examples: http://msdn.microsoft.com/en-us/library/8kb3ddd4.aspx

Upvotes: 0

Sam Harwell
Sam Harwell

Reputation: 99869

This pulls the current thread's culture information for formatting:

// short time pattern, could be "6:30 AM" or "6:30"
DateTime.Now.ToString("t", CultureInfo.CurrentCulture)
// long time pattern, could be "6:30:00 AM" or "6:30:00"
DateTime.Now.ToString("T", CultureInfo.CurrentCulture)

And this pulls the current operating system's (Windows) installed culture information for formatting:

DateTime.Now.ToString("t", CultureInfo.InstalledUICulture)
DateTime.Now.ToString("T", CultureInfo.InstalledUICulture)

Edit to show just the time.

Upvotes: 6

Related Questions