DateTime.AddDays() 未按预期工作 [英] DateTime.AddDays() not working as expected

查看:24
本文介绍了DateTime.AddDays() 未按预期工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个简单的程序:

        DateTime aux = new DateTime(2012, 6, 12, 12, 24, 0);
        DateTime aux2 = new DateTime(2012, 6, 12, 13, 24, 0);
        aux2.AddDays(1);

       Console.WriteLine((aux2 - aux).TotalHours.ToString());

        Console.ReadLine();

我调试了这个并发现 aux2.AddDays(1); 似乎不起作用,我在这里遗漏了什么?它应该返回 25,但答案是 1.

I debugged this and found aux2.AddDays(1); doesn't seem to work, what am I missing here? it should return 25 but the answer is one.

有什么问题?

还有 AddHours 不起作用,我猜其他人也不起作用.

also AddHours doesn't work, I guess that the others aren't working too.

推荐答案

它确实有效,但你没有对返回值做任何事情,试试

It does work but you don't do anything with the return value, try

aux2 = aux2.AddDays(1);

DateTimes 与 Strings 共享不变性的这一方面.

DateTimes share this facet of immutability with Strings.

编辑

MSDN

此方法不会更改此 DateTime 的值.相反,它返回一个新的 DateTime,其值是此操作的结果.

This method does not change the value of this DateTime. Instead, it returns a new DateTime whose value is the result of this operation.

这篇关于DateTime.AddDays() 未按预期工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆