简体   繁体   中英

DateTime.TryParseExact cannot resolve yyyyMMddHmmss format

Why DateParse cannot resolve yyyyMMddHmmss for below case?

var data = "2017011762000";
if (DateTime.TryParseExact(field, "yyyyMMddHmmss", CultureInfo.InvariantCulture,
                DateTimeStyles.None, out var result))
{
   return result;
}

I dont want to parse hours like HH beacuse my input is not adding the 0 on the begging. And its 24h clock.

According to the docs .

If you do not use date or time separators in a custom format pattern, use the invariant culture for the provider parameter and the widest form of each custom format specifier . For example, if you want to specify hours in the pattern, specify the wider form, "HH", instead of the narrower form, "H".

As pointed out by others -- including spaces have added separators to the format string.

TryParse is expecting HH instead of H . You can add a 0 manually

var data = "2017011762000";
data = data.Insert(8, "0");
if (DateTime.TryParseExact(data, "yyyyMMddHmmss", CultureInfo.InvariantCulture,
                DateTimeStyles.None, out var result))
{
   return result;
}

How do you handle the case when the hour is 11 for example anyway? In case you will have 2 digits then, I guess you can do something like this to add the 0 only when its needed:

if(data.Length==13)
    data = data.Insert(8, "0");

But my advise would be to fix the issue at the source (where you receive the data from) if you can.

EDIT: Jasen's answer covers why it will not work with the current format of the string.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM