Disappointed
Disappointed

Reputation: 1120

How to add hours to date considering DST

How to add hours to date considering DST ?
We have time shift at 27 of October, so i expect to get 19(or 21) hour in result.
How can i do that ?

  var test = new DateTimeOffset(new DateTime(2018, 10, 26, 20, 0, 0));
  var test2 = test.AddHours(48);

Upvotes: 3

Views: 1514

Answers (3)

Maxter
Maxter

Reputation: 824

Convert DateTime to UTC:

var dateLocal = new DateTime(2018, 10, 26, 20, 0, 0);
var dateUTC = dateLocal.ToUniversalTime();

Add the hours:

dateUTC = dateUTC.AddHours(48);

Convert back to local time:

dateLocal = dateUTC.ToLocalTime();

Upvotes: 3

Jon Skeet
Jon Skeet

Reputation: 1503090

The simplest approach is to convert to UTC, add the 48 hours there, then convert back. That way you apply the appropriate time zone offset at each point. For example:

using System;

class Test
{
    static void Main()
    {
        var test = new DateTimeOffset(new DateTime(2018, 10, 26, 20, 0, 0));
        var test2 = test.AddHours(48);
        var test3 = test.ToUniversalTime().AddHours(48).ToLocalTime();
        Console.WriteLine(test2);
        Console.WriteLine(test3);
    }
}

Results in the London time zone:

28/10/2018 20:00:00 +01:00
28/10/2018 19:00:00 +00:00

Note that in some cases the original local time could be skipped or ambiguous though - you should consider what to do then. I'd personally (for obvious reasons) recommend my Noda Time project for this instead, where there are more types to represent the different kinds of value you'd work with. Decisions like how to deal with skipped/ambiguous times are more obvious because you basically have to make them.

Upvotes: 9

Austin T French
Austin T French

Reputation: 5140

There is a built in way to check for DST, you could do arithmitic based on that similar to:

var test = new DateTimeOffset(new DateTime(2018, 11, 4, 0, 0, 0));
var newTime = test.AddHours(2);

if (test.LocalDateTime.IsDaylightSavingTime() && 
     !newTime.LocalDateTime.IsDaylightSavingTime())
        {
            test = test.AddHours(-1);
        }

You might also look at nodatime.

Upvotes: 0

Related Questions