[英]DateTime error Subtracting from 0 hour
Using C# DateTime, I'd like to subtract a time past 0 (or midnight). 使用C#DateTime,我想减去0(或午夜)之后的时间。 However, I get an error when doing so. 但是,这样做时会出现错误。 I'm trying to create a timeline where you can zoom in and out and scroll through the times. 我正在尝试创建一个时间轴,您可以在其中放大和缩小以及滚动浏览时间。 I get the following error: "The added or subtracted value results in an un-representable DateTime." 我收到以下错误:“相加或相减的值导致无法表示的DateTime。”
I guess DateTime doesn't know how to wrap back around from 0 to 23? 我猜DateTime不知道如何从0到23回绕? How do I get around this? 我该如何解决?
If you subtract a TimeSpan
from a DateTime
, it will "wrap around" past midnight: 如果从DateTime
减去TimeSpan
,它将在午夜之后“环绕”:
> var d1 = DateTime.Parse("4/11/2012 12:30:00 AM");
> var d2 = d1.Subtract(new TimeSpan(1, 15, 0));
>
> d2
[4/10/2012 11:15:00 PM]
My guess is that you're using the date which starts at DateTime.MinValue
. 我的猜测是您正在使用以DateTime.MinValue
开始的DateTime.MinValue
。 If you subtract time such that it would go before DateTime.MinValue
, you'll get that exception. 如果您减去时间以使它早于DateTime.MinValue
,则会得到该异常。
// This is equal to DateTime.MinValue - maybe you're doing this?
DateTime date = new DateTime();
// Bang
date = date.AddHours(-1);
If you really want a "just a time" representation, consider using Noda Time , my pseudo-port of Joda Time with a rather richer type system than just DateTime
. 如果您真的想要“只是一个时间”表示形式,请考虑使用Noda Time (我的Joda Time伪端口),其类型系统比DateTime
更丰富。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.