本文介绍了为什么DateTime.AddHours似乎不起作用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有相同的结果1338161400当我做
I have same result 1338161400 when I do
DateTime origin = new DateTime(1970, 1, 1, 0, 0, 0, 0);
DateTime date = DateTime.Parse(@"28/05/12 01:30");
TimeSpan diff = date.ToUniversalTime() - origin;
Console.WriteLine( (Math.Floor(diff.TotalSeconds)).ToString());
以及当我使用date.AddHours(-4):
as well as when I use date.AddHours(-4) :
DateTime origin = new DateTime(1970, 1, 1, 0, 0, 0, 0);
DateTime date = DateTime.Parse(@"28/05/12 01:30");
date.AddHours(-4);
TimeSpan diff = date.ToUniversalTime() - origin;
Console.WriteLine( (Math.Floor(diff.TotalSeconds)).ToString());
我尝试得到1338168600像
I try to get 1338168600 like http://www.mbari.org/staff/rich/utccalc.htm
更新:
感谢我更改为
DateTime origin = new DateTime(1970, 1, 1, 0, 0, 0, 0);
DateTime date = DateTime.Parse(@"28/05/2012 01:30");
date = date.AddHours(-4);
date = date.ToUniversalTime();
TimeSpan diff = date - origin;
Console.WriteLine((Math.Floor(diff.TotalSeconds)).ToString());
但是我还有1338147000还没有1338168600
But I got 1338147000 still not 1338168600
推荐答案
日期是不可变的对象,即创建后无法修改。 DateTime.AddHours返回一个新的DateTime实例,该实例向后移动4个小时,但date将不被修改。
Dates are immutable objects, i.e. they cannot be modified after creation. DateTime.AddHours returns a new DateTime instance which is shifted backwards by 4 hours but "date" will not be modified.
使用:
DateTime newDate = date.AddHours(-4);
这篇关于为什么DateTime.AddHours似乎不起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!