tags:

views:

208

answers:

6

Hi, I want to convert a C# DateTime to "YYYYMMDDHHMMSS" format. But I don't find a built in method to get this format? Any comments?

+25  A: 

You've practically written the format yourself.

yourdate.ToString("yyyyMMddHHmmss")

  • MM = two digit month
  • mm = two digit minutes
  • HH = two digit hour, 24 hour clock
  • hh = two digit hour, 12 hour clock

Everything else should be self-explanatory.

Anthony Pegram
+11  A: 

You've just got to be careful between months (MM) and minutes (mm):

DateTime dt = DateTime.Now; // Or whatever
string s = dt.ToString("yyyyMMddHHmmss");

(Also note that HH is 24 hour clock, whereas hh would be 12 hour clock, usually in conjunction with t or tt for the am/pm designator.)

If you want to do this as part of a composite format string, you'd use:

string s = string.Format("The date/time is: {0:yyyyMMddHHmmss}", dt);

For further information, see the MSDN page on custom date and time formats.

Jon Skeet
Good point Thanks!!!, I was reading your articles and now its nice that you asnwered my question. Thanks Dude.
SARAVAN
+4  A: 
DateTime.Now.ToString("yyyyMMddHHmmss");

if you just want it displayed as a string

Pharabus
+8  A: 

DateTime.Now.ToString("yyyyMMddHHmmss"); // case sensitive

Jim Lamb
+6  A: 

You can use a custom format string:

DateTime d = DateTime.Now;
string dateString = d.ToString("yyyyMMddHHmmss");

Substitute "hh" for "HH" if you do not want 24-hour clock time.

Paul Kearney - pk
A: 

DateTime.Now.ToString("sameAsYourQuestion");

Spike