C# DateTime to “YYYYMMDDHHMMSS” format

后端 未结 18 1764
故里飘歌
故里飘歌 2020-11-22 01:53

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?

18条回答
  •  无人共我
    2020-11-22 02:50

    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.

提交回复
热议问题