Add minutes to date during time changing

I want to add minutes to date where time is changing. Eg.

In 24-10-2015 time at 3 o'clock time goes back one hour in the back.

So when we have 2:20 AM, 50 minutes later we have 2:10 AM.

var date = new DateTime(2015,10,24, 2,20, 00);
Console.WriteLine(date.AddMinutes(50).ToString());

Above code return 3:10 and it's wrong.

How can I fix it? It's depends on the country and timezone.

Jon Skeet
people
quotationmark

This sort of thing is precisely why I started the Noda Time project. It teases out assumptions you might have. For example, in your example, 2:20am occurs twice - so when you say new DateTime(2015,10,24, 2,20, 00) how is the system meant to know whether you mean the first occurrence or the second? It's not even clear which time zone you expect it to be in.

In Noda Time, the code would be something like:

var local = new LocalDateTime(2015, 10, 24, 2, 20, 0);
var zone = DateTimeZoneProviders.Tzdb[yourTimeZoneId];

// Apparently you want ambiguous times to resolve as the earlier
// occurrence.
var resolver = Resolvers.CreateMappingResolver(
    Resolvers.ReturnEarlier, Resolvers.ThrowWhenSkipped);

// This is now the *first* occurrence of 2:20am
var zoned = local.InZone(zone, resolver);

// This is now the *second* occurrence of 2:10am
var laterZoned = zoned.Plus(Duration.FromMinutes(50));

Note how everything is a lot more explicit here. You don't have to create your own resolver, in many cases - you can use InZoneStrictly which will throw on ambiguous or skipped times, and InZoneLeniently which will take the later of the ambiguous times, and the start of the interval after the gap for skipped times. (Some of this is changing slightly for Noda Time 2.0, hopefully to make things simpler for common cases.)

people

See more on this question at Stackoverflow