Convert DateTime Format in C#

前端 未结 4 1583
攒了一身酷
攒了一身酷 2021-01-25 03:03

How can I convert this datetime format from a webservice. The datetime value is: \"timestamp\": \"2014-04-18T14:45:00+02:00\" I wan\'t to convert it to: dd.mm.YYYY hh.mm.ss

4条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-01-25 03:34

    You need to use "yyyy-MM-dd'T'HH:mm:ssK" format with InvariantCulture using DateTime.ParseExact method like;

    string s = "2014-04-18T14:45:00+02:00";
    var date = DateTime.ParseExact(s, "yyyy-MM-dd'T'HH:mm:ssK",
                                       CultureInfo.InvariantCulture);
    

    Take a look at The "K" Custom Format Specifier

    Then you can get string representation of your DateTime with DateTime.ToString() method. DateTime has no inherent format, it has just a value. You can get string representation for formatting.

    date.ToString("dd.MM.yyyy HH.mm.ss", CultureInfo.InvariantCulture);
    //18.04.2014 03.45.00
    

    Here a demonstration.

    Remember, mm is for minutes, MM for months. And hh is for 12-hour clock which is 01 to 12. But HH is 24-hour clock which is 00 to 23.

    That's why you can't parse 14 with hh specifier. I assume your real representation format is dd.MM.yyyy HH.mm.ss

    EDIT: After your comment, you can use "MM/dd/yyyy HH:mm:ss" format like;

    string s = "04/18/2014 14:45:00";
    var date = DateTime.ParseExact(s, "MM/dd/yyyy HH:mm:ss",
                                       CultureInfo.InvariantCulture);
    Console.WriteLine(date); // 18/04/2014 14:45:00
    

提交回复
热议问题