convert string to datetime with form yyyy-MM-dd HH:mm:ss in C#

前端 未结 2 470
故里飘歌
故里飘歌 2020-12-16 18:06

How can I convert this 2014-01-01 23:00:00 to DateTime I have done like this:

Console.WriteLine(DateTime.ParseExact(\"2014-01-01 23         


        
相关标签:
2条回答
  • 2020-12-16 18:40

    I think your parsing worked. The problem is when converting back to string. You can provide the desired format in parameter :

    DateTime date = DateTime.ParseExact("2010-01-01 23:00:00", "yyyy-MM-dd HH:mm:ss", CultureInfo.InvariantCulture);
    string formattedDate = date.ToString("yyyy-MM-dd HH:mm:ss")
    Console.WriteLine(formattedDate);
    

    By default (without a specified format), it uses formatting information derived from the current culture.

    0 讨论(0)
  • 2020-12-16 18:45

    Because 2014-01-01 23:00:00 IS 2014-01-01 11:00:00 PM.

    Better explanation

    You are implicitly calling DateTime.ToString(), which by default uses the General ("G") format, which in the en-US culture is MM/dd/yyyy hh:mm:ss tt.

    If you want to display the time in a different format, you need to specify it:

    string s = DateTime.ParseExact("2010-01-01 23:00:00", "yyyy-MM-dd HH:mm:ss", CultureInfo.InvariantCulture);
    Console.WriteLine(s.ToString("yyyy-MM-dd HH:mm:ss");
    

    Or since you're using the same format string, just store it:

    string format = "yyyy-MM-dd HH:mm:ss";
    DateTime dt = DateTime.ParseExact("2010-01-01 23:00:00", format , CultureInfo.InvariantCulture);
    Console.WriteLine(s.ToString(format);
    
    0 讨论(0)
提交回复
热议问题