简体   繁体   中英

Date and time conversion in C# - DateTime.ParseExact() not working as expected

I have date/time format, for example: "1-Mar-13 92230" According to this document and this link the format is as follows: "d-MMM-yy Hmmss", because:

Day is single digit, 1-30
Month is 3 letter abbreviation, Jan/Mar etc.
Year is 2 digits, eg 12/13
Hour is single digit for 24 hour clock, eg 9, 13 etc. (no 09)
Minute is standard (eg 01, 52)
Second is standard (eg 30, 02)

I'm trying to run the following code in my program, but I keep getting an error of "String was not recognized as a valid DateTime."

string input = "1-Mar-13 92330";
        var date = DateTime.ParseExact(input, "d-MMM-yy Hmmss", 
System.Globalization.CultureInfo.CurrentCulture);

Please help, I'm not too familiar with DateTime conversions, but I can't see where I've gone wrong here. Thanks!

UPDATE: Is this because time cannot be parsed without colons in between? (eg 1-Mar-13 9:22:30 gets parsed, but i have an external data source that would be impossible to rewrite from Hmmss to H:mm:ss)

You could fix your date:

var parts = "1-Mar-13 92230".Split(' ');

if (parts[1].Length == 5)
{
    parts[1] = "0" + parts[1];
}

var newDate = parts[0] + " " + parts[1];

var date = DateTime.ParseExact(newDate, "d-MMM-yy HHmmss",  System.Globalization.CultureInfo.CurrentCulture);

From msdn :

If format is a custom format pattern that does not include date or time separators (such as "yyyyMMdd HHmm"), 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".

so you can try:

string input = "1-Mar-13 92330";
        var date = DateTime.ParseExact(input, "d-MMM-yy Hmmss", 
System.Globalization.CultureInfo.InvariantCulture);

Your input string has to be of following format

string input = "1-Mar-13 092330";

If you go back to your link, it says

H   24-hour clock hour (e.g. 19)

Now H is 24 hours, it should be represented with leading 0. If not imagine how would you handle the case of hours greater than 9 ie which are in double digit.

If not your hour and Minute and Seconds has to be separated.

string input = "1-Mar-13 9 2330";

var date = DateTime.ParseExact(input, "d-MMM-yy H mmss", 
System.Globalization.CultureInfo.InvariantCulture);

Your hour min and seconds need to be separated, as they are not getting distinguished.

string input = "1-Mar-13 9 23 30";
        var date = DateTime.ParseExact(input, "d-MMM-yy H mm ss",   System.Globalization.CultureInfo.CurrentCulture);

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