Why DateTime.AddHours doesn't seem to work?

0

Issue

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

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

I try to get 1338168600 like http://www.mbari.org/staff/rich/utccalc.htm

Update:

Thanks I changed to

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

But I got 1338147000 still not 1338168600

Solution

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.

Use:

DateTime newDate = date.AddHours(-4);

Answered By – Slugart

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave A Reply

Your email address will not be published.

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More