Nate Pet
Nate Pet

Reputation: 46222

c# Time Display AM PM

I know we can do the following to show AM PM for a Time.

    String.Format("{0:t}", dt);  // "4:05 PM" 

What if I want to show A for AM and P for PM. Is there a format for that?

Upvotes: 3

Views: 9027

Answers (4)

Marlon
Marlon

Reputation: 20314

Another solution would be to use the System.Globalization.DateTimeFormatInfo class which allows you to specify how you want your AM/PM to be formatted:

DateTimeFormatInfo timeFormat = new DateTimeFormatInfo();
timeFormat.ShortTimePattern = CultureInfo.CurrentCulture.DateTimeFormat.ShortTimePattern;
timeFormat.AMDesignator = "A";
timeFormat.PMDesignator = "P";

// Both of these are the same:
string a = DateTime.Now.ToString("t", timeFormat);
string b = String.Format(timeFormat, "{0:t}", DateTime.Now);

You can do completely custom stuff with it:

timeFormat.AMDesignator = "cookies";
timeFormat.PMDesignator = "bagels";

Example output for 4:05 PM:

4:05 bagels

Upvotes: 7

the_joric
the_joric

Reputation: 12226

use "t":

Console.Out.WriteLine("date1 = {0:hh:mm:ss.F t}", DateTime.Now);
// date1 = 12:49:35.4 A

(more details on http://msdn.microsoft.com/en-us/library/8kb3ddd4.aspx#tSpecifier)

Upvotes: 2

Babak Naffas
Babak Naffas

Reputation: 12561

Have you tried

String.Format("{0:h:mm t}", DateTime.Now)

Upvotes: 3

Shankar
Shankar

Reputation: 157

Not sure, but you could probably use ? String.Format().IndexOf("AM") > 0 ? "A" : "P"

Upvotes: 0

Related Questions