Search code examples
c#.netdatetime

How to parse "string" to "DateTime" with "a. m." or "p. m." format (not AM/PM)?


I need to convert this DateTime string("6/12/2018 12:00:03 a. m.") to DateTime type using the function DateTime.ParseExact().

I converted the string using this option and it works:

var date = "6/01/2018  12:00:03 a. m.";
var x = Convert.ToDateTime(date);

Also I was able to convert this string("6/12/2018 12:00:03") using DateTime.ParseExact() but when the date doesn´t contain the indicator a. m. or p. m.:

var date = "6/01/2018  12:00:03";
var x = DateTime.ParseExact(date, "d/MM/yyyy  h:mm:ss", CultureInfo.InvariantCulture);

How can I convert that datetime string when the time part contains the a. m. or p. m. part using DateTime.ParseExact() function?


Solution

  • This is what the tt custom format specifier are for.

    var date = "6/01/2018  12:00:03 am";
    var x = DateTime.ParseExact(date, "d/MM/yyyy  h:mm:ss tt", CultureInfo.InvariantCulture);
    

    But remember, this tt specifier does not parse a. m. or a.m. strings. If your strings have those, you have to manipulate your strings like removing dots and/or spaces between a and m etc.. It also parse AM and PM as well.