C# DateTime conversion when time changes from winter to summer time - c#

I am getting this error:
The supplied DateTime represents an invalid time. For example, when
the clock is adjusted forward, any time in the period that is skipped
is invalid
when I try to convert time 2020-03-29 02:30 from Eastern European Time (GMT+2) to UTC time.
According to this site the clock should change at 03:00 for Finland, which means that time 02:30 should be possible to convert to UTC.
But when I run the following code, an exception is thrown.
var timezoneMap = TimeZoneInfo.GetSystemTimeZones().ToDictionary(x => x.Id, x => x);
var timezoneInfo = timezoneMap["E. Europe Standard Time"];
var localTime1 = DateTime.SpecifyKind(new DateTime(2020, 12, 15, 0, 0, 0), DateTimeKind.Unspecified);
var localTime2 = DateTime.SpecifyKind(new DateTime(2020, 3, 29, 2, 30, 0), DateTimeKind.Unspecified);
var utc1 = TimeZoneInfo.ConvertTimeToUtc(localTime1, timezoneInfo); // 2020-12-14 22:00 correct
var utc2 = TimeZoneInfo.ConvertTimeToUtc(localTime2, timezoneInfo); // throws exception
What is wrong with the second conversion, why is there an exception?

The site you're looking at uses the IANA time zone data, which I believe to be accurate.
But your code uses the Windows time zone database, which in this case looks like it has a discrepancy... it seems to think that the transition is at midnight UTC rather than 1am UTC. Here's code to demonstrate that:
using System;
using System.Globalization;
class Program
{
static void Main()
{
var zone = TimeZoneInfo.FindSystemTimeZoneById("E. Europe Standard Time");
// Start at 2020-03-28T23:00Z - definitely before the transition
var utc = new DateTime(2020, 3, 28, 23, 0, 0, DateTimeKind.Utc);
for (int i = 0; i < 8; i++)
{
var local = TimeZoneInfo.ConvertTime(utc, zone);
Console.WriteLine($"{utc:yyyy-MM-dd HH:mm} UTC => {local:yyyy-MM-dd HH:mm} local");
utc = utc.AddMinutes(30);
}
}
}
Output (annotated):
2020-03-28 23:00 UTC => 2020-03-29 01:00 local
2020-03-28 23:30 UTC => 2020-03-29 01:30 local
2020-03-29 00:00 UTC => 2020-03-29 03:00 local <= Note the change here, at midnight UTC
2020-03-29 00:30 UTC => 2020-03-29 03:30 local
2020-03-29 01:00 UTC => 2020-03-29 04:00 local
2020-03-29 01:30 UTC => 2020-03-29 04:30 local
2020-03-29 02:00 UTC => 2020-03-29 05:00 local
2020-03-29 02:30 UTC => 2020-03-29 05:30 local
The current IANA data definitely does say 1am UTC, as shown in this line of the rules. So I believe the web site is correctly interpreting the data, and it's just a matter of the Windows time zone database being "different" (and, I suspect, incorrect).

Related

Convert DateTime to DateTimeOffset taking into account SummerTime

Consider the code below. I have a list of dates around the point in time when CEST changes from summer to winter time. I need to convert them to UTC. However using this code the midnight gets lost, I can't understand how to fix it.
DateTime firstDate = new DateTime(2020, 10, 24, 21, 0, 0);
DateTime lastDate = new DateTime(2020, 10, 25, 3, 0, 0);
DateTime[] dates = Enumerable.Range(0, (lastDate - firstDate).Hours + 1)
.Select(r => firstDate.AddHours(r))
.ToArray();
TimeZoneInfo tzo = TimeZoneInfo.FindSystemTimeZoneById("Central European Standard Time");
List<DateTimeOffset> offsets = new List<DateTimeOffset>();
foreach(var date in dates)
{
var timeSpan = tzo.GetUtcOffset(date);
var offset = new DateTimeOffset(date, timeSpan);
offsets.Add(offset);
}
10/24/2020 09:00:00 PM +02:00 = 19:00Z
10/24/2020 10:00:00 PM +02:00 = 20:00Z
10/24/2020 11:00:00 PM +02:00 = 21:00Z
10/25/2020 12:00:00 AM +02:00 = 22:00Z
10/25/2020 01:00:00 AM +02:00 = 23:00Z
10/25/2020 02:00:00 AM +01:00 = 01:00Z - What happened to 00:00Z?
10/25/2020 03:00:00 AM +01:00 = 02:00Z
You're converting from what I'd call a "local date/time" to a UTC value. Some local date/time values are skipped and some are repeated, due to daylight saving transitions (and other time zone changes).
In the situation you're showing, every local time between 2am inclusive and 3am exclusive happened twice, because at 3am (the first time) the clocks went back to 2am - this line:
10/25/2020 02:00:00 AM +01:00 = 01:00Z
... shows the second mapping of 2am. But at 2020-10-25T00:00:00Z the local time was also 2am due to the clocks going back. Your conversion is ambiguous, in other words.
The TimeZoneInfo documentation states:
If dateTime is ambiguous, or if the converted time is ambiguous, this method interprets the ambiguous time as a standard time.
Here, "standard time" is the second occurrence of any ambiguous time (because it's a transition from daylight time to standard time).
Fundamentally, if you only have local values then you have incomplete information. If you want to treat ambiguous values as daylight time instead of standard time (or flag them up as ambiguous), you can always use TimeZoneInfo.IsAmbiguousTime(DateTime) to detect that.
The problem is that there are two 2AM's on 25th October 2020 - 02:00 AM +02:00 and 02:00 AM +01:00.
Since the source DateTime has no offset available, the GetUtcOffset method has no way to determine which 2AM the value refers to, and so it defaults to using the non-DST offset - 02:00 AM +01:00.
Depending on what you're actually trying to do, you may be able to resolve this by converting the start time to UTC, generating a list of UTC DateTimeOffset values, and then converting them back to the desired time-zone:
DateTime firstDate = new DateTime(2020, 10, 24, 21, 0, 0);
TimeZoneInfo tzo = TimeZoneInfo.FindSystemTimeZoneById("Central European Standard Time");
DateTimeOffset firstDateUtc = TimeZoneInfo.ConvertTime(firstDate, tzo, TimeZoneInfo.Utc);
DateTimeOffset[] utcDates = Enumerable.Range(0, 7).Select(r => firstDateUtc.AddHours(r)).ToArray();
DateTimeOffset[] offsets = Array.ConvertAll(utcDates, d => TimeZoneInfo.ConvertTime(d, tzo));
Output:
24/10/2020 21:00:00 +02:00
24/10/2020 22:00:00 +02:00
24/10/2020 23:00:00 +02:00
25/10/2020 00:00:00 +02:00
25/10/2020 01:00:00 +02:00
25/10/2020 02:00:00 +02:00
25/10/2020 02:00:00 +01:00
Alternatively, you might want to look at NodaTime, which provides a much clearer model for working with dates and times.

How to check if an hour exists in a specific Time Zone in .NET

During a Daylight Saving Time transition, the clock is moved forward, and so a specific hour will not exist in that specific day for that specific time zone.
Is there an easy way in .NET to find out if an hour exists or not for a time zone?
The only way I found was by trying to convert an hour to UTC, and check for an exception:
public bool IsValidTime(DateTime date, TimeZoneInfo tzi)
{
try
{
date = DateTime.SpecifyKind(date, DateTimeKind.Unspecified);
TimeZoneInfo.ConvertTimeToUtc(date, tzi);
return true;
}
catch
{
return false;
}
}
And so running something like this will return false:
var date = new DateTime(2020, 3, 8);
var tzi = TimeZoneInfo.FindSystemTimeZoneById("Cuba Standard Time");
var isValid = IsValidTime(date, tzi);
Is there any built in way of doing this, that is less messy?
You can use IsInvalidTime method of TimeZoneInfo.
From Microsoft : https://learn.microsoft.com/en-us/dotnet/api/system.timezoneinfo.isinvalidtime?view=netframework-4.6.2
Example: In the Pacific Time zone, daylight saving time begins at 2:00 A.M. on April 2, 2006. The following code passes the time at one-minute intervals from 1:59 A.M. on April 2, 2006, to 3:01 A.M. on April 2, 2006, to the IsInvalidTime method of a TimeZoneInfo object that represents the Pacific Time zone. The console output indicates that all times from 2:00 A.M. on April 2, 2006, to 2:59 A.M. on April 2, 2006, are invalid.
// Specify DateTimeKind in Date constructor
DateTime baseTime = new DateTime(2007, 3, 11, 1, 59, 0, DateTimeKind.Unspecified);
DateTime newTime;
// Get Pacific Standard Time zone
TimeZoneInfo pstZone = TimeZoneInfo.FindSystemTimeZoneById("Pacific Standard Time");
// List possible invalid times for a 63-minute interval, from 1:59 AM to 3:01 AM
for (int ctr = 0; ctr < 63; ctr++)
{
// Because of assignment, newTime.Kind is also DateTimeKind.Unspecified
newTime = baseTime.AddMinutes(ctr);
Console.WriteLine("{0} is invalid: {1}", newTime, pstZone.IsInvalidTime(newTime));
}

Converting time zones in C#

I have written a code which basically pulls out transactions from my DB in a PST time zone. What I'd like to do then is simply convert those dates into CEST time zone and IST (Israel Standard Time).
I did something like following :
var transactions = ctx.UserStores.Where(x => x.UserId == loggedUser.UserId).SelectMany(x => x.StoreItems.SelectMany(y => y.StoreItemTransactions)).ToList();
var hourlyData = transactions
.GroupBy(x => TimeZoneInfo.ConvertTime(x.TransactionDate.Value, TimeZoneInfo.FindSystemTimeZoneById(timeZone)).Hour)
.Select(pr => new HourlyGraph { Hour = pr.Key, Sales = pr.Sum(x => x.QuantitySoldTransaction) })
.ToList();
where timeZone parameter can be one of following:
Central European Standard Time
Israel Standard Time
Pacific Standard Time
Naurally when timeZone parameter is = PST I would expect the same results in my list... But the weird thing is the results get completely shuffled up and I'm not sure why ...
So the dates in my DB are kept in PST time zone and I'm trying to convert them into one of these 3 above time zones...
What am I doing wrong here??
Sample code that uses the version of TimeZoneInfo.ConvertTime which expects both a source and target timezone.
DateTime sourceTime = new DateTime(2015, 6, 10, 10, 20, 30, DateTimeKind.Unspecified);
TimeZoneInfo sourceTimeZone = TimeZoneInfo.FindSystemTimeZoneById("Pacific Standard Time");
foreach(var targetTimeZoneID in new string[] { "Pacific Standard Time", "Israel Standard Time", "Central European Standard Time" })
{
TimeZoneInfo targetTimeZone = TimeZoneInfo.FindSystemTimeZoneById(targetTimeZoneID);
var converted = TimeZoneInfo.ConvertTime(sourceTime, sourceTimeZone, targetTimeZone);
Console.WriteLine("{0}: {1:yyyy-MM-dd HH:mm:ss}", targetTimeZoneID, converted);
}
Console.ReadLine();
Output is:
Pacific Standard Time: 2015-06-10 10:20:30 Israel Standard Time:
2015-06-10 20:20:30 Central European Standard Time: 2015-06-10
19:20:30

Working with DateTimeOffset

I have some problems understanding the DateTimeOffset...
I am trying to create a simple-trigger for a Quartz-Job.
There exists a triggerbuilder with which one can create such a trigger like this:
var triggerbuilder =
TriggerBuilder.Create()
.WithIdentity(triggerName, ConstantDefinitions.InternalDefinitions.AdhocJobGroup)
.StartAt(new DateTimeOffset(scheduledTime));
The scheduledTime is a DateTime. Let's say it is new DateTime(2014, 10, 15, 14, 0, 0);
I live in a city which lies in the Central European Time Zone (UTC+01:00).
When I print
var dto = new DateTimeOffset(new DateTime(2014, 10, 15, 14, 0, 0));
Console.WriteLine(dto);
I get the following result:
15.10.2014 14:00:00 +02:00
What does the +02:00 exactly mean? And why is it +2:00 and not +01:00?
Does that mean, that my trigger will be started at 16:00 instead of 14:00?
Thanks in advance
15.10.2014 14:00:00 +02:00 is a datetimeoffset (datetime + timezone) representing 2pm local time in a timezone of +2 UTC
this is equivalent to 15.10.2014 12:00:00 in UTC
With regard to why is it +02:00 rather than +01:00, is daylight savings active?
Converting Between DateTime and DateTimeOffset

Are adding weeks, months or years to a date/time independent from time zone?

My software displays date/time using local time and then send it to server in UTC. On the server-side I want to add months, years, weeks, days etc to this date/time. However, the question is, if I use such methods with UTC date/time and then convert it back to local time, would the result be always the same, as if I use this methods with local time directly?
This is an example in C#:
// #1
var utc = DateTime.Now.ToUtcTime();
utc = utc.AddWeeks(2); // or AddDays, AddYears, AddMonths...
var localtime = utc.ToLocalTime();
// #2
var localtime = DateTime.Now;
localtime = localtime.AddWeeks(2); // or AddDays, AddYears, AddMonths...
Would the results in #1 and #2 always be the same? Or timezone can influence the result?
The answer may surprise you but it is NO. You cannot add days, weeks, months, or years to a UTC timestamp, convert it to a local time zone, and expect to have the same result as if you had added directly to the local time.
The reason is that not all local days have 24 hours. Depending on the time zone, the rules for that zone, and whether DST is transitioning in the period in question, some "days" may have 23, 23.5, 24, 24.5 or 25 hours. (If you are trying to be precise, then instead use the term "standard days" to indicate you mean exactly 24 hours.)
As an example, first set your computer to one of the USA time zones that changes for DST, such as Pacific Time or Eastern Time. Then run these examples:
This one covers the 2013 "spring-forward" transition:
DateTime local1 = new DateTime(2013, 3, 10, 0, 0, 0, DateTimeKind.Local);
DateTime local2 = local1.AddDays(1);
DateTime utc1 = local1.ToUniversalTime();
DateTime utc2 = utc1.AddDays(1);
DateTime local3 = utc2.ToLocalTime();
Debug.WriteLine(local2); // 3/11/2013 12:00:00 AM
Debug.WriteLine(local3); // 3/11/2013 1:00:00 AM
And this one covers the 2013 "fall-back" transition:
DateTime local1 = new DateTime(2013, 11, 3, 0, 0, 0, DateTimeKind.Local);
DateTime local2 = local1.AddDays(1);
DateTime utc1 = local1.ToUniversalTime();
DateTime utc2 = utc1.AddDays(1);
DateTime local3 = utc2.ToLocalTime();
Debug.WriteLine(local2); // 11/4/2013 12:00:00 AM
Debug.WriteLine(local3); // 11/3/2013 11:00:00 PM
As you can see in both examples - the result was an hour off, one direction or the other.
A couple of other points:
There is no AddWeeks method. Multiply by 7 and add days instead.
There is no ToUtcTime method. I think you were looking for ToUniversalTime.
Don't call DateTime.Now.ToUniversalTime(). That is redundant since inside .Now it has to take the UTC time and convert to local time anyway. Instead, use DateTime.UtcNow.
If this code is running on a server, you shouldn't be calling .Now or .ToLocalTime or ever working with DateTime that has a Local kind. If you do, then you are introducing the time zone of the server - not of the user. If your users are not in the same time zone, or if you ever deploy your application somewhere else, you will have problems.
If you want to avoid these kind of problems, then look into NodaTime. It's API will prevent you from making common mistakes.
Here's what you should be doing instead:
// on the client
DateTime local = new DateTime(2013, 3, 10, 0, 0, 0, DateTimeKind.Local);
DateTime utc = local.ToUniversalTime();
string zoneId = TimeZoneInfo.Local.Id;
// send both utc time and zone to the server
// ...
// on the server
TimeZoneInfo tzi = TimeZoneInfo.FindSystemTimeZoneById(zoneId);
DateTime theirTime = TimeZoneInfo.ConvertTimeFromUtc(utc, tzi);
DateTime newDate = theirTime.AddDays(1);
Debug.WriteLine(newDate); // 3/11/2013 12:00:00 AM
And just for good measure, here is how it would look if you used Noda Time instead:
// on the client
LocalDateTime local = new LocalDateTime(2013, 3, 10, 0, 0, 0);
DateTimeZone zone = DateTimeZoneProviders.Tzdb.GetSystemDefault();
ZonedDateTime zdt = local.InZoneStrictly(zone);
// send zdt to server
// ...
// on the server
LocalDateTime newDate = zdt.LocalDateTime.PlusDays(1);
Debug.WriteLine(newDate); // 3/11/2013 12:00:00 AM

Categories