简体   繁体   中英

DateTime.ParseExact not working in C#, Date format Conversion not working

Parse Time not working as I want to convert "13-06-2019 00:00:00"(dd-MM-yyyy HH:mm:ss) to "06-13-2019 00:00:00"(MM-dd-yyyy HH:mm:ss)

tried with Convert.toDateTime() and DateTime.ParseExact()

IFormatProvider culture = new CultureInfo("en-US");
var a = DateTime.ParseExact(a, "MM-dd-yyyy hh:mm:ss", CultureInfo.InvariantCulture);
var b = DateTime.ParseExact(a, "yyyy-MM-dd HH:mm:ss", null);
var c = DateTime.ParseExact(a, "yyyy-MM-dd HH:mm:ss", culture);

Nothing working in it

DateTime structure uses Gregorian calendar under the hood and there is no 13th month in that calendar.

So, parsing 13 with MM specifier is wrong. I strongly suspect that you try to use dd-MM-yyyy HH:mm:ss format instead.

string a = "13-06-2019 00:00:00";
DateTime  b = DateTime.ParseExact(a, "dd-MM-yyyy HH:mm:ss", CultureInfo.InvariantCulture);

Here a demonstration

Your second and third examples also don't work since their formats are completely different than your string. When you parse your string with ParseExact method , your strings and your format should match exactly .

Also I want to mention that, both hh and HH specifiers would work in my code example. But as a general format consideration, using dd-MM-yyyy HH:mm:ss format is much more common and reliable than the other option.

The format parameter of DateTime.ParseExact(date,format,culture) is the source format of the date string to be converted and the return value is type date which you can convert back to string as per the desired format.

var a = "13-06-2019 00:00:00";

IFormatProvider culture = new CultureInfo("en-US");
DateTime b = DateTime.ParseExact(a, "dd-MM-yyyy hh:mm:ss", CultureInfo.InvariantCulture);

Console.WriteLine($"{b:MM-dd-yyyy HH:mm:ss}");

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