Advertisement
Advertisement


C# DateTime to "YYYYMMDDHHMMSS" format


Question

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?

2010/06/11
1
635
6/11/2010 6:43:49 PM

Accepted Answer

DateTime.Now.ToString("yyyyMMddHHmmss"); // case sensitive
2018/06/26
1088
6/26/2018 3:29:57 PM


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.

2010/06/11

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.

2010/06/11

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.

2010/06/11

If you use ReSharper, get help with ':' (see image)

Intellisense

2020/06/20

DateTime.Now.ToString("yyyyMMddHHmmss");

if you just want it displayed as a string

2010/06/11

Source: https://stackoverflow.com/questions/3025361
Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Email: [email protected]