Bonomi
Bonomi

Reputation: 2743

DateTime to string format in c#

I am having some trouble converting a DateTime variable to string. I want to display the time using a 12-hour clock including the AM/PM

With the following code:

string timeStr = PaymentDate.ToString("hh:mm tt");

I will get "11:39" but the PM/AM is not showing. Any guess?

Upvotes: 0

Views: 460

Answers (2)

Soner Gönül
Soner Gönül

Reputation: 98750

DateTime.ToString(string) method uses your CurrentCulture by default.

I think your DateTimeFormat's AMDesignator is empty string. That's why you can't print it with your CurrentCulture.

As an alternative, you can use InvariantCulture (which has "AM" as a AMDesignator) as a second parameter in DateTime.ToString overload.

string timeStr = PaymentDate.ToString("hh:mm tt", CultureInfo.InvariantCulture);

Inspector Gadget mode on: Your profile page says you are from Ireland and I assume your CurrentCulture is en-IE. And it's AMDesignator property value is empty string.

CultureInfo.GetCultureInfo("en-IE").DateTimeFormat.AMDesignator;
// Prints empty string

Upvotes: 3

Tim Schmelter
Tim Schmelter

Reputation: 460138

You can use CultureInfo.InvariantCulture to force the AM/PM designator even if your current culture doesn't use it:

PaymentDate.ToString("hh:mm tt", CultureInfo.InvariantCulture);

You can check what your current culture's designator is by (mine is also "" in "de-DE"):

DateTimeFormatInfo.CurrentInfo.AMDesignator  // and .PMDesignator

Upvotes: 4

Related Questions