[英]An unhandled exception of type 'System.FormatException' occurred in mscorlib.dll
[英]When trying to parse DateTime - An unhandled exception of type 'System.FormatException' occurred in mscorlib.dll
我要减去两个不同的日期,但是当我尝试显示相减的值时,它就会与标题中的消息一起崩溃An unhandled exception of type 'System.FormatException' occurred in mscorlib.dll
。 奇怪的是,当我尝试显示DateTime
时,我正在使用相同的方法。
这是我的(编辑)代码:
//works fine
DateTime startingTime = DateTime.Now;
System.Windows.MessageBox.Show(startingTime.ToString("HH:mm:ss", CultureInfo.InvariantCulture));
Thread.Sleep(1000);
//works fine
DateTime newTime = DateTime.Now;
System.Windows.MessageBox.Show(newTime.ToString("HH:mm:ss", CultureInfo.InvariantCulture));
//EXCEPTION
System.Windows.MessageBox.Show((newTime - startingTime).ToString("HH:mm:ss", CultureInfo.InvariantCulture));
我也尝试使用TimeSpan
和newTime.Subtract(startingTime)
,但是返回相同的异常。
仅当我尝试以格式HH:mm:ss
解析该异常时,才会发生该异常。 如果我仅使用ToString()
,则效果很好,但这不是我想要的格式。
因为newTime - startingTime
返回TimeSpan
并且其格式与DateTime
不同。
我相信这会奏效;
string.Format("{0:HH\\:mm\\:ss}", (newTime - startingTime))
但这适用于.NET Framework 4+。 如果您使用的是.NET 3.5或更低版本,则可以使用;否则。
TimeSpan ts = newTime - startingTime;
string.Format("{0:00}:{1:00}:{2:00}",
(int)ts.TotalHours,
ts.Minutes,
ts.Seconds);
您应该使用:
(newTime - startingTime).ToString("c")
它将TimeSpan
格式设置为hh:mm:ss
。 由于此默认格式对区域性不敏感,因此无需传递CultureInfo
。
或者,为避免出现毫秒问题(只是Soner更好的第二个答案的替代方法):
TimeSpan.FromSeconds(Math.Floor(newTime - startingTime.TotalSeconds)).ToString("c")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.