将 TimeSpan 添加到给定的 DateTime
我只想向 DateTime
添加 1 天。所以我写道:
DateTime date = new DateTime(2010, 4, 29, 10, 25, 00);
TimeSpan t = new TimeSpan(1, 0, 0, 0);
date.Add(t);
Console.WriteLine("A day after the day: " + date.ToString());
我认为结果将是: 2010 04 30- 10:25:00
但我仍然得到初始日期。
怎么了?
I just want to add 1 day to a DateTime
. So I wrote:
DateTime date = new DateTime(2010, 4, 29, 10, 25, 00);
TimeSpan t = new TimeSpan(1, 0, 0, 0);
date.Add(t);
Console.WriteLine("A day after the day: " + date.ToString());
I thought the result would be: 2010 04 30- 10:25:00
but I'm still getting the initial date.
What's wrong?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(8)
DateTime 值不可变。 Add 方法返回一个新的 DateTime 值与 TimeSpan。
这有效:
DateTime values are immutable. The Add method returns a new DateTime value with the TimeSpan added.
This works:
您需要更改一行:
You need to change a line:
dtb 关于
DateTime
不可变的说法是正确的。可以这样想:DateTime
是一种值类型,这将其与int
或double
归为同一类别。这些结构的实例不能被修改;它们只能被评估和复制。考虑这段代码:
这类似于:
顺便说一句,可能有助于使这一点更清楚的一件事是认识到上面的行
d = d.Add(t)
与d = d + t
。而且您不会在自己的行上编写d + t
,就像您不会在自己的行上编写i + 2
一样。dtb is right about
DateTime
being immutable. Think of it this way: aDateTime
is a value type, which puts it in the same category asint
ordouble
. Instances of these structures cannot be modified; they can only be evaluated and copied.Consider this code:
This is analogous to:
By the way, one thing that might help make this clearer is realizing that the above line,
d = d.Add(t)
, is the same asd = d + t
. And you wouldn't writed + t
on its own line, just like you wouldn't writei + 2
on its own line.DateTime 是不可变的,但 Add 和 Subtract 函数会返回新的 DateTime 供您使用。
A DateTime is immutable, but the Add and Subtract functions return new DateTimes for you to use.
仅仅执行
date = date.AddDays(1)
有什么问题吗?What is wrong with just doing
date = date.AddDays(1)
?date.Add(t) 的结果就是您想要的:
The result of date.Add(t) is what you're after:
返回修改后的 DateTime,并且不会更改您调用 Add 方法的原始实例。
returns a modified DateTime and does not change the original instance on which you call the Add method on.
如果 DateTime obj 数据类型是“DateTime?”,DateTime 将不起作用哪个接受空值,在这种情况下
DateTime? dt = DateTime.Now;
DateTime wont work if DateTime obj datatype is "DateTime?" which takes accepts null values, in such case
DateTime? dt = DateTime.Now;