C# TimeSpan未获得正确的剩余时间
我有一句话:C# TimeSpan未获得正确的剩余时间,c#,timespan,C#,Timespan,我有一句话: TimeSpan duration = Convert.ToDateTime(localSettings.Containers["userInfo"].Values["nextSpinUnlockTime"]) - Convert.ToDateTime(localSettings.Containers["userInfo"].Values["spinTimeStarted"]); 如果本地容器中的nextSpinUnlockTime存储了2015年8月
TimeSpan duration =
Convert.ToDateTime(localSettings.Containers["userInfo"].Values["nextSpinUnlockTime"])
- Convert.ToDateTime(localSettings.Containers["userInfo"].Values["spinTimeStarted"]);
如果本地容器中的nextSpinUnlockTime
存储了2015年8月11日10:54:23和spinTimeStarted
存储了2015年8月11日07:54:23,为什么持续时间
存储了800毫秒
有人知道怎么回事吗
我只调试那一行,那一行的持续时间等于-800毫秒
更新
我有这个(我忘了提和补充):
我已经调试过了,出现负毫秒的原因是因为没有按预期增加3小时。有人知道为什么吗 尝试使用
DateTime.Subtract()
:
您可能需要检查持续时间。DateTime
的totalmillizes默认值ToString()
方法将值设置为秒:
因此,在您的情况下,两个值都有毫秒,但不会打印出来:
DateTime first = new DateTime(2015, 11, 8, 10, 54, 23, 900);
DateTime second = new DateTime(2015, 11, 8, 10, 54, 23, 100);
TimeSpan duration = second - first;
// The output:
// 08.11.2015 10:54:23 <- default ToString() - up to seconds
// 08.11.2015 10:54:23 <- default ToString() - up to seconds
// -00:00:00.8000000
Console.Write(String.Join(Environment.NewLine, first, second, duration));
DateTime first=新的日期时间(2015,11,8,10,54,23900);
DateTime second=新的日期时间(2015,11,8,10,54,23100);
TimeSpan持续时间=秒-第一;
//输出:
//2015年11月8日10:54:23问题必须出现在Convert.ToDateTime调用中。在你的例子中我看不到任何毫秒。为什么不尝试向convert方法提供一些有关区域性的详细信息
CultureInfo culture = new CultureInfo("en-GB");
var start = Convert.ToDateTime("11/08/2015 10:54:23", culture);
在很长一段时间我的头撞在桌子上之后,我试着:
DateTime newDate = currentDateAndTime.AddHours(3);
当它添加额外的3小时时,结果是正确的,我知道DateTime
对象是不可变的,但我不明白为什么它不起作用,因为我没有将值赋回currentDateAndTime
,例如:
currentDateAndTime = currentDateAndTime.AddHours(3);
相反,我在做:
localSettings.Containers["userInfo"].Values["nextSpinUnlockTime"] = Convert.ToDateTime(localSettings.Containers["userInfo"].Values["spinTimeStarted"]).AddHours(3).ToString();
然而,它起作用了,我再高兴不过了
谢谢大家 为什么有两种不同格式的日期?您是否真正检查过返回的DateTime
值?例如将它们分配到不同的变量中,并查看它们的精确值。@RonBeyer这只是为了计算不同状态下的差异这里不足以重现问题,但我猜是utc中的一个,另一个是本地的。我同意@SonerGönül。将解析和减法分开,这样您就可以轻松地调试并准确地看到您的输入被解析成的DateTime
值。DateTime.Subtract
和操作符-(DateTime,DateTime)
将给出相同的结果。是的,但要排除(事实上不应该是这样)重载操作符,最好使用预期的.Subtract(DateTime)
函数。不过,我仍然支持.totalmillists
部分。他在寻找3个小时时提到了.millides
存储-800
,但我没有看到他在查看.hours
或.TotalHours
属性。根据日期时间,totalmillides
和millides
,800都是错误的,因此,虽然知道差异很重要,但我严重怀疑它与根本问题有关。如果他减去的值实际上是3小时800毫秒的差异,在他的示例中,TimeSpan对象duration
将具有以下内容:duration.Millisecond=-800
和duration.Hours=-3
,而duration.totalmillimes=-10800800
和duration.TotalHours=-3
。感谢您的提醒。不幸的是,答案并非如此
DateTime newDate = currentDateAndTime.AddHours(3);
currentDateAndTime = currentDateAndTime.AddHours(3);
localSettings.Containers["userInfo"].Values["nextSpinUnlockTime"] = Convert.ToDateTime(localSettings.Containers["userInfo"].Values["spinTimeStarted"]).AddHours(3).ToString();