Not recognising hours Mins and seconds as part of a valid date format

0

Trying to parse this string into a datetime variable:

var test = "2018 11 24 17 3 57 345";
var format = "yyyy MM dd HH mm ss fff";
var dt = DateTime.ParseExact(dt, format, CultureInfo.InvariantCulture);

I get this error:

System.FormatException HResult=0x80131537 Message=String '2018 11 24 17 3 57 345' was not recognized as a valid DateTime. Source=System.Private.CoreLib StackTrace: at System.DateTime.ParseExact(String s, String format, IFormatProvider provider) line 28

c#
date-conversion
asked on Stack Overflow Nov 24, 2018 by Andrew Simpson

1 Answer

1
var test = "2018 11 24 17 3 57 345";
var format = "yyyy MM dd HH m ss fff";
var dt = DateTime.ParseExact(dt, format, CultureInfo.InvariantCulture);

mm is 00-59, m is 0-59.

To support both, supply two formats:

var test = "2018 11 24 17 3 57 345";
var format = "yyyy MM dd HH m ss fff";
var format2 = "yyyy MM dd HH mm ss fff";
var dt = DateTime.ParseExact(dt, new string[] { format, format2 }, CultureInfo.InvariantCulture);
answered on Stack Overflow Nov 24, 2018 by JLe • edited Nov 24, 2018 by JLe

User contributions licensed under CC BY-SA 3.0