简体   繁体   中英

How to convert datetime string in format MMMdyyyyhhmmtt to datetime object?

I have tried like below:

DateTime.ParseExact("Feb520161000PM", 
"MMMdyyyyhhmmtt", CultureInfo.InvariantCulture)

But it's giving FormatException .

Interestingly

DateTime.ParseExact(DateTime.Now.ToString("MMMdyyyyhhmmtt"), "MMMdyyyyhhmmtt", 
CultureInfo.InvariantCulture)

This is also giving format exception.

The format is not parseable with regular parsing which work from left to right - you need custom code that parses value from right to left instead as you want leftmost number to be variable width ("Feb111111111PM").

If possible - change format to one with fixed width fields (preferably ISO8601). Otherwise split string manually and construct date from resulting parts (time part would work fine by itself, so just need to manually parse date part).

Some other approaches and info can be found in similar post about time - DateTime.ParseExact - how to parse single- and double-digit hours with same format string?

Alexei's answer is quite right, I wanna explain little bit deep if you let me..

You are thinking 5 should match with d specifier, right? But this is not how DateTime.ParseExact works under the hood .

Since The "d" custom format specifier represents number from 1 through 31 , this specifier will map 52 in your string, not just 5 . That's why your code throws FormatException .

As you can see, your string format can't parsed unless you do it some string manipulations with it.

In such a case, .NET Team suggests either using two digit forms like 05 or insert separators for your date and time values.

You can create a custom method that parse this MMMdyyyyhhmmtt format for only parse this kind of formatted strings like;

public static DateTime? ParseDate_MMMdyyyyhhmmtt(string date)
{
    if (date == null)
        return null;
    if (date.Length < 14)
        return null;
    if (date.Length == 14)
        date = date.Insert(3, "0");
    DateTime dt;
    if (DateTime.TryParseExact(date, "MMMdyyyyhhmmtt",
                               CultureInfo.InvariantCulture,
                               DateTimeStyles.None, out dt))
        return dt;
    return null;
}

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