C# DateTime to “YYYYMMDDHHMMSS” format

后端 未结 18 1569
故里飘歌
故里飘歌 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:44

    An easy Method, Full control over 'from type' and 'to type', and only need to remember this code for future castings

    DateTime.ParseExact(InputDate, "dd/MM/yyyy", CultureInfo.InvariantCulture).ToString("yyyy/MM/dd"));
    
    0 讨论(0)
  • 2020-11-22 02:45

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

    0 讨论(0)
  • 2020-11-22 02:45

    I am surprised no one has a link for this . any format can be created using the guidelines here:

    Custom Date and Time Format Strings

    For your specific example (As others have indicated) use something like

    my_format="yyyyMMddHHmmss";
    DateTime.Now.ToString(my_format);
    

    Where my_format can be any string combination of y,M,H,m,s,f,F and more! Check out the link.

    0 讨论(0)
  • 2020-11-22 02:45

    Get the date as a DateTime object instead of a String. Then you can format it as you want.

    • MM/dd/yyyy 08/22/2006
    • ffffdd, dd MMMM yyyy Tuesday, 22 August 2006
    • ffffdd, dd MMMM yyyy HH:mm Tuesday, 22 August 2006 06:30
    • ffffdd, dd MMMM yyyy hh:mm tt Tuesday, 22 August 2006 06:30 AM
    • ffffdd, dd MMMM yyyy H:mm Tuesday, 22 August 2006 6:30
    • ffffdd, dd MMMM yyyy h:mm tt Tuesday, 22 August 2006 6:30 AM
    • ffffdd, dd MMMM yyyy HH:mm:ss Tuesday, 22 August 2006 06:30:07
    • MM/dd/yyyy HH:mm 08/22/2006 06:30
    • MM/dd/yyyy hh:mm tt 08/22/2006 06:30 AM
    • MM/dd/yyyy H:mm 08/22/2006 6:30
    • MM/dd/yyyy h:mm tt 08/22/2006 6:30 AM
    • MM/dd/yyyy HH:mm:ss 08/22/2006 06:30:07

    Click here for more patterns

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-11-22 02:52

    It is not a big deal. you can simply put like this

    WriteLine($"{DateTime.Now.ToString("yyyy-MM-dd-HH:mm:ss")}");
    

    Excuse here for I used $ which is for string Interpolation .

    0 讨论(0)
提交回复
热议问题