一尘不染

为什么DateTime.AddHours似乎不起作用?

c#

我有相同的结果1338161400

    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)时:

    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());

我尝试获得像http://www.mbari.org/staff/rich/utccalc.htm的
1338168600

更新:

谢谢我更改为

    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


阅读 495

收藏
2020-05-19

共1个答案

一尘不染

日期是不可变的对象,即创建后无法修改。DateTime.AddHours返回一个新的DateTime实例,该实例向后移4小时,但不会修改“日期”。

采用:

DateTime newDate = date.AddHours(-4);
2020-05-19