Home DateTime.ParseExact using just hour format not working
Reply: 0

DateTime.ParseExact using just hour format not working

user2446
1#
user2446 Published in June 19, 2018, 2:24 pm

In my net core project I have to parse a string into a DateTime. The format is dynamic and not known at compilation time. The code is:

var datetime = DateTime.ParseExact(data, format, CultureInfo.InvariantCulture, DateTimeStyles.None);

but I'm having issues when the format is just the hour and is coming as numbers from 0 to 23. According to this article to specify the hour format you have 4 options: h, hh, H and HH, but when trying to parse "0"

Using h I get:

System.FormatException : Input string was not in a correct format.

Using hh I get:

System.FormatException: String was not recognized as a valid DateTime.

Using H I get:

System.FormatException : Input string was not in a correct format.

Using HH I get:

System.FormatException: String was not recognized as a valid DateTime.

In this article it is stated that

If format is a custom format pattern that does not include date or time separators (such as "yyyyMMddHHmm"), 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 format pattern, specify the wider form, "HH", instead of the narrower form, "H".

but it is what i have been doing and is not working. I cannot guess how to achieve parsing a string which is just the hour into a DateTime. Any ideas??

EDIT

The exception is thrown when executing any of these lines:

DateTime.ParseExact("0", "HH", CultureInfo.InvariantCulture, DateTimeStyles.None);
DateTime.ParseExact("0", "H", CultureInfo.InvariantCulture, DateTimeStyles.None);

I cannot use TimeSpan.Parse as I have a generic solution to read xlsx files. How to read the file is stored on the datatabase. Sometimes the DateTime is all in one column and the format is ddMMyyHHmmss and others the DateTime is in one column with the format ddMMyy and the hour in other as a number from 0 to 23 (minutes and seconds should be initialized with 0). Later the date and hour are merged to return the whole DateTime.

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.586404 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO