简体   繁体   English

DateTime.ParseExact 在 C# 中不起作用,日期格式转换不起作用

[英]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)解析时间不起作用,因为我想将 "13-06-2019 00:00:00"(dd-MM-yyyy HH:mm:ss) 转换为 "06-13-2019 00:00:00"(MM-dd -yyyy HH:mm:ss)

tried with Convert.toDateTime() and DateTime.ParseExact()尝试使用Convert.toDateTime()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. DateTime结构在DateTime使用公历,并且该日历中没有第 13 个月。

So, parsing 13 with MM specifier is wrong.所以,用MM说明符解析13是错误的。 I strongly suspect that you try to use dd-MM-yyyy HH:mm:ss format instead.我强烈怀疑您尝试使用dd-MM-yyyy HH:mm:ss格式。

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 .当您使用ParseExact方法解析您的字符串时,您的字符串和您的格式应该完全匹配

Also I want to mention that, both hh and HH specifiers would work in my code example.另外我想提一下, hhHH说明符都可以在我的代码示例中使用。 But as a general format consideration, using dd-MM-yyyy HH:mm:ss format is much more common and reliable than the other option.但作为一般格式考虑,使用dd-MM-yyyy HH:mm:ss格式比其他选项更常见和可靠。

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. DateTime.ParseExact(date,format,culture) 的格式参数是要转换的日期字符串的源格式,返回值是日期类型,您可以根据所需格式将其转换回字符串。

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}");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM