英文:
how to parse a string to DateTime in c#?
问题
我想从C#中的dt1(2023-01-01)中减去dt2(2023-12-31),但当我尝试调试代码时,它显示“System.FormatException:'字符串'2023-12-31 08:00:00'无法识别为有效的DateTime。'”
我的代码:
DateTime dt1 = DateTime.Parse("2023-01-01 08:00:00");
DateTime dt2 = DateTime.Parse("2023-12-31 08:00:00");
TimeSpan diff = dt2.Subtract(dt1);
Console.WriteLine(diff.ToString());
如何修复这个错误?
英文:
I want to subtract dt2 (2023-12-31) from dt1 (2023-01-01) in c#, but when i try to debug the codes it says " System.FormatException: 'String '2023-12-31 08:00:00' was not recognized as a valid DateTime.' "
my codes:
DateTime dt1 = DateTime.Parse("2023-01-01 08:00:00");
DateTime dt2 = DateTime.Parse("2023-12-31 08:00:00");
TimeSpan diff = dt2.Subtract(dt1);
Console.WriteLine(diff.ToString());
How i can fix this error?
答案1
得分: 6
你的问题与DateTime相减无关,而是在解析它们时发生异常。问题在于DateTime.Parse
在没有传递其他信息时使用当前区域设置的信息(如日期分隔符)。看起来你来自伊朗,所以让我们复现这个异常:
System.Threading.Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("fa-IR");
DateTime dt2 = DateTime.Parse("2023-12-31 08:00:00");
修复的一种方法是传递CultureInfo.InvariantCulture
:
DateTime dt1 = DateTime.Parse("2023-01-01 08:00:00", CultureInfo.InvariantCulture);
DateTime dt2 = DateTime.Parse("2023-12-31 08:00:00", CultureInfo.InvariantCulture);
英文:
Your issue is not about subtracting DateTimes but the exception happens when you parse them. The reason is that DateTime.Parse
uses your current culture's information(like date-separator) when you don't pass another. It seems that you are from iran, so this lets reproduce the exception:
System.Threading.Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("fa-IR");
DateTime dt2 = DateTime.Parse("2023-12-31 08:00:00");
So one way to fix it is to pass CultureInfo.InvariantCulture
:
DateTime dt1 = DateTime.Parse("2023-01-01 08:00:00", CultureInfo.InvariantCulture);
DateTime dt2 = DateTime.Parse("2023-12-31 08:00:00", CultureInfo.InvariantCulture);
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论