如何在C#中将字符串解析为DateTime?

huangapple go评论68阅读模式
英文:

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。'”
如何在C#中将字符串解析为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.' "
如何在C#中将字符串解析为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);

huangapple
  • 本文由 发表于 2023年5月13日 15:35:59
  • 转载请务必保留本文链接:https://go.coder-hub.com/76241590.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定