KentZhou
KentZhou

Reputation: 25553

datetime string issue in c#

Suppose I have following code to convert datetime to string:

DateTime dt;
//...
string ds = dt.ToString("dd/MM/yyyy hh:mm")

If the dt is 15/02/2009 08:22, I want to the string is 15/02/2009 08:22AM If the dt is 15/02/2009 20:22, I want to the string is 15/02/2009 08:22PM

How to implement it?

Upvotes: 2

Views: 182

Answers (4)

Harsh Vyas
Harsh Vyas

Reputation: 326

DateTime dt;

string ds = dt.ToString("dd/MM/yyyy hh:mmtt");

Upvotes: 0

Ryan Alford
Ryan Alford

Reputation: 7594

you should use lowercase "t"...

DateTime dt;
//...
string ds = dt.ToString("dd/MM/yyyy hh:mmtt")

Upvotes: 1

Lasse V. Karlsen
Lasse V. Karlsen

Reputation: 391276

As per the documentation of DateTime.ToString, the characters you need to add are t's, so this should work:

string ds = dt.ToString("dd/MM/yyyy hh:mmtt")

One 't' would give you 'P' or 'A', and two will give you 'PM' or 'AM'.

Note that depending on your current CultureInfo, you might, or might not, get the AM/PM.

Upvotes: 5

scottm
scottm

Reputation: 28703

use this:

string ds = dt.ToString("dd/MM/yyyy hh:mmtt")

Here are all of the available options for converting DateTime to string

Upvotes: 13

Related Questions