简体   繁体   中英

DateTime.TryParseExact() is returning false

I have the following code

public static void Main()
{
    DateTime D = new DateTime();
    D = DateTime.Now;

    string s1 = D.ToString("ddMMMMyyyy");
    Console.WriteLine(s1);

    Console.WriteLine(DateTime.TryParseExact(s1, "ddMMMyyyy", CultureInfo.InvariantCulture, DateTimeStyles.None, out D));
    Console.ReadKey();
}

Could someone please help me realise the obvious mistake I am making.

I converted DateTime.Now into a string in a custom format and tried to convert it back, but TryParseExact is returning false.

Short answer: MMMM does not equal MMM .

A Sidenote: parsing such strings with CultureInfo.InvariantCulture will only recognize English names, it seems that it will fail on machines with other languages.

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