Using TimeZoneInfo to adjust a timezone's daylight-savings offset - c#

Below is the method I use that takes in three inputs:
dateTimeInput which is a string that represents a date.
inputFormat are my format strings like this format: yyyy-MM-dd'T'HH:mm:sszzz.
timeZoneStandardName are unique timezone identifiers retrieved from var TimeZoneList = TimeZoneInfo.GetSystemTimeZones(); where the ID is retrieved via timeZoneList.Id.
I mainly used TimeZoneInfo to get my hours and minute offsets because it's very explicit as to what city/timezone it is, e.g. UTC is the input string.
public int dateTimeToUnixTime(string dateTimeInput, string inputFormat, string timeZoneStandardName)
{
DateTime result;
CultureInfo provider = CultureInfo.InvariantCulture;
TimeZoneInfo objTimeZoneInfo = TimeZoneInfo.FindSystemTimeZoneById(timeZoneStandardName);
int timeZoneHours = objTimeZoneInfo.BaseUtcOffset.Hours;
int timeZoneMinutes = objTimeZoneInfo.BaseUtcOffset.Minutes;
// if input format is "yyyy-MM-dd'T'HH:mm:sszzz"
if (inputFormat == "yyyy-MM-dd'T'HH:mm:sszzz")
{
result = DateTime.ParseExact(dateTimeInput, inputFormat, provider, DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal);
int unixTime = (Int32)(result.Subtract(Epoch)).TotalSeconds;
return unixTime;
}
else
{
// if other input formats
result = DateTime.ParseExact(dateTimeInput, inputFormat, provider, DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal);
int unixTime = (Int32)(result.AddHours(-timeZoneHours).AddMinutes(-timeZoneMinutes).Subtract(Epoch)).TotalSeconds;
return unixTime;
}
}
My second method takes in a Unix timestamp and a timezone specifier and outputs as a location-dependent time:
public string unixTimeToDateTime(int unixInput, string outputFormat, string timeZoneStandardName)
{
// output format is "yyyy-MM-dd'T'HH:mm:sszzz"
TimeZoneInfo objTimeZoneInfo = TimeZoneInfo.FindSystemTimeZoneById(timeZoneStandardName);
int timeZoneHours = objTimeZoneInfo.BaseUtcOffset.Hours;
int timeZoneMinutes = objTimeZoneInfo.BaseUtcOffset.Minutes;
if (outputFormat == "yyyy-MM-dd'T'HH:mm:sszzz")
{
System.DateTime dateTime = Epoch.AddSeconds(unixInput);
return dateTime.AddHours(timeZoneHours).AddMinutes(timeZoneMinutes).ToString("yyyy-MM-dd'T'HH:mm:ss") + toTimeSpan(timeZoneHours, timeZoneMinutes);
}
// output format is not
else
{
System.DateTime dateTime = Epoch.AddSeconds(unixInput).AddHours(timeZoneHours).AddMinutes(timeZoneMinutes);
return dateTime.ToString(outputFormat);
}
}
For example, here is this method in a Grasshopper component for me to show you what I mean. dateTimeToUnixTime() is my first "clock", while unixTimeToDateTime() is my second "clock"
Given an input of those list of times and a timezone marker of EST, and given those dates (mind you November 2nd 2014 1-2 AM is when we get our DST adjustments again), this method theoretically should adjust its timezone to offset an hour.
I know that TimeZoneInfo supports DST because I can use the below method to show a bool of a respective timezone's DST status.
var TimeZoneList = TimeZoneInfo.GetSystemTimeZones();
for (int i = 0; i < TimeZoneList.Count; i++)
{
Console.WriteLine(TimeZoneList[i].Id + ": " + TimeZoneList[i].SupportsDaylightSavingTime);
}
My question is, what is missing in my dateTimeToUnixTime() method that would allow automatic adjustment and offset depending on the DST conditions?

Assuming that your epoch starts at 1/1/1970, then we can use a DateTimeOffset _1970 as your epoch, add the required seconds to _1970 and then use TimeZoneInfo.ConvertTime to get a date time in the specified time zone with daylight savings adjustments (if applicable). It is important to use a DateTimeOffset and not DateTime so that the correct offset will be kept when getting the string.
private static readonly DateTimeOffset _1970 = new DateTimeOffset(1970, 1, 1, 0, 0, 0, TimeSpan.Zero);
public string UnixTimeToDateTime(int unixInput, string outputFormat, string timeZoneStandardName)
{
var objTimeZoneInfo = TimeZoneInfo.FindSystemTimeZoneById(timeZoneStandardName);
var utcDate = _1970.AddSeconds(unixInput);
DateTimeOffset localDate = TimeZoneInfo.ConvertTime(utcDate, objTimeZoneInfo);
return localDate.ToString(outputFormat);
}
//1970-01-01T13:00:00+13:00
Console.WriteLine( UnixTimeToDateTime(0, "yyyy-MM-dd'T'HH:mm:sszzz", "New Zealand Standard Time"));
//1970-01-01T08:00:00+08:00
Console.WriteLine(UnixTimeToDateTime(0, "yyyy-MM-dd'T'HH:mm:sszzz", "Singapore Standard Time"));
//1969-12-31T19:00:00-05:00
Console.WriteLine(UnixTimeToDateTime(0, "yyyy-MM-dd'T'HH:mm:sszzz", "Eastern Standard Time"));
It is important to note that using TimeZoneInfo may not have accurate information about historical date adjustments, so if that is important to you, then you may be better using a library such as Node Time.

Related

NodaTime timezone abbreviation from Instant

Got an excel export feature where the datetime column should be localized based on the browser location (14-Nov-2022 12:51 PM EST). Using NodaTime, I am able to localize it. However, I am not able to get the timezone abbreviation (PST, EST, CST etc..,) which needs to be appended at the end of the datetime string.
public static string ToSpecificTimeZone(this DateTimeOffset utcDateTime, int offset)
{
var offsetTimeSpan = TimeSpan.FromMinutes(offset);
var localizedDateTime =
Instant.FromDateTimeOffset(new DateTimeOffset(utcDateTime.DateTime, offsetTimeSpan));
var localizedDateTimeString = localizedDateTime.ToString("dd-MMM-yyyy hh:mm tt", CultureInfo.InvariantCulture);
return localizedDateTimeString;
}
I used this logic to get the zone abbreviation for system default, but dont know how to get it for dynamic offsets,
var zone = DateTimeZoneProviders.Tzdb.GetSystemDefault();
var zonedDateTime = SystemClock.Instance.GetCurrentInstant().InZone(zone);
var zoneName = zonedDateTime.Zone.GetZoneInterval(zonedDateTime.ToInstant()).Name;
Any tips or directions would be really helpful.

Get DateTime object given local time as string, date as UTC DateTime and a timezone-locale string?

I'm working with data from several sources, and I need to put together an accurate DateTime.
I have:
A) a string representing a time of day, e.g.: "4:00 pm"
B) a DateTime object intended to represent a pure date, by having been created as midnight, zulu time (offset of 00:00) for a particular date.
C) a string representing a timezone locale, e.g.: "America/Los_Angeles"
How do I get a precise DateTime object, with correct number of ticks, representing the time (A) experienced in that locale (C), on that date (B)??
Here you have an example using NodaTime, which is more reliable of any of the framework classes when dealing with calendars, time zones, dates and times:
var timeString = "4:00 pm";
var pureDate = new DateTime(2017, 5, 22, 0, 0, 0, DateTimeKind.Utc);
var timezoneString = "America/Los_Angeles";
var localTime = ParseTimeString(timeString);
var localDate = LocalDate.FromDateTime(pureDate);
var localDateTime = localDate.At(localTime);
var zone = DateTimeZoneProviders.Tzdb[timezoneString];
var zonedDateTime = localDateTime.InZoneStrictly(zone);
Inside zonedDateTime you will find your full date:
"2017-05-22T16:00:00 America/Los_Angeles (-07)"
You may than use zonedDateTime.ToDateTimeUtc() to get a System.DateTime instance in UTC.
ParseTimeString parses your time string using your format specifier:
public static LocalTime ParseTimeString(string timeString)
{
var pattern = LocalTimePattern.CreateWithInvariantCulture("h:mm tt");
return pattern.Parse(timeString).Value;
}
Considerations if you use DateTime, DateTimeOffset and TimeZoneInfo
If you do not want to use NodaTime be aware of the possible pitfalls of the built-in classes:
TimeZoneInfo in Windows uses a different specifier that is not compatible with IANA/TZDB. Your America/Los_Angeles time zone string will not work if you do not convert it before use (see https://stackoverflow.com/tags/timezone/info)
DateTimeOffset (which is more reliable then DateTime) still loses information when created. The time zone data cannot be persisted and you will have just a date with an offset from UTC.
You'll need to manually parse your custom time string (maybe using regexes).
Here's how I ended up working it out w/o NodaTime:
public static DateTime Combine(DateTime date, string time, string timeZone)
{
TimeZoneInfo tzInfo = TimeZoneInfo.FindSystemTimeZoneById(TimezoneDictionary[timeZone]);
var timeOfDay = DateTime.ParseExact(time, "h:mm tt", null).TimeOfDay;
var combined = date.Add(timeOfDay).Subtract(tzInfo.BaseUtcOffset);
if (tzInfo.IsDaylightSavingTime(combined))
combined = combined.Subtract(TimeSpan.FromHours(1));
return combined;
}
I also need this dictionary to convert IANA timezones to Microsoft:
private static Dictionary<string, string> TimezoneDictionary = new Dictionary<string, string>
{
{ "America/Los_Angeles", "Pacific Standard Time" },
{ "America/Denver", "Mountain Standard Time" },
{ "America/Chicago", "Central Standard Time" },
{ "America/New_York", "Eastern Standard Time" },
//many more of course, just clipping this list for brevity.
};

Convert from one timezone to another taking into consideration daylight saving

I want to convert a datetime from one time zone to another. For this i need to pass the zone id to the method FindSystemTimeZoneById. But i do not have this information and need to determine that by using a switch-case.
Here i also need to take into account daylight saving. but in order to determine whether a time is in DST i need that zone id beforehand.
Is there any way to determine whether a time is in DST without the zone id. My server is in zone 1 and i want to convert the time to zone 2.
Here is the snippet:
public DateTime ConvertToDestTime(DateTime currentTime, string sourceTimeZoneUtc, string serverTimeZoneUtc)
{
TimeZoneInfo sourceTimeZone = TimeZoneInfo.FindSystemTimeZoneById(ReturnTimeZoneString(sourceTimeZoneUtc));
TimeZoneInfo serverTimeZone = TimeZoneInfo.FindSystemTimeZoneById(ReturnTimeZoneString(serverTimeZoneUtc));
DateTime serverTime = TimeZoneInfo.ConvertTime(currentTime, sourceTimeZone, serverTimeZone);
return serverTime;
}
private string ReturnTimeZone(string utcOffset)
{
string timezone = string.Empty;
string isDaylight = //need to determine whether time is in DST here
if (isDaylight == "N")
{
switch (utcOffset)
{
case "-04:00":
timezone = "Atlantic Standard Time";
break;
case "-05:00":
timezone = "Eastern Standard Time";
break;
}
}
else
{
switch (utcOffset)
{
case "-04:00":
timezone = "Eastern Standard Time";
break;
case "-05:00":
timezone = "Central America Standard Time";
break;
}
}
return timezone;
Convert the source time to UTC time.
string sourceTimeZone="Atlantic Standard Time;
TimeZoneInfo timeZoneInfo = TimeZoneInfo.FindSystemTimeZoneById(sourceTimeZone);
DateTime sourceUTCTime = TimeZoneInfo.ConvertTimeToUtc(currentTime, timeZoneInfo);
then using the converted UTC time get the destination time as below,
string destinationTimeZone="India Standard Time";
TimeZoneInfo destTimeZoneInfo = TimeZoneInfo.FindSystemTimeZoneById(destinationTimeZone);
DateTime destinationUTCTime = TimeZoneInfo.ConvertTimeFromUtc(sourceUTCTime, destTimeZoneInfo);
Hope this helps!!!
Check ou t Microsoft's "timeless" article Coding Best Practices Using DateTime in the .NET Framework.
The article may be a few years old, but the priciples and problem scenarios are still today's topics.
There is a dedicated chapter about Dealing with Daylight Savings Time.
By converting your local time views to universal time prior to
performing your calculations, you get past the issues of time
accuracy.
So, convert your local time to UTC format first and then into the target time format.
You cannot perform this type of reverse mapping reliably. There are just two many possible time zones that any particular offset could fall into.
See "TimeZone != Offset" in the timezone tag wiki.
See also all the places that -04:00 might be used.
Lastly, recognize that because each time zone in North America falls-back in their own local time, some values are shared by two time zones at once.
For example, 2014-11-02T01:00:00-05:00 could belong to either US Central Time (CDT) or US Eastern Time (EST), as shown here.
A bit old question, but may be somebody will enjoy bellow extension
public static class DateTimeExtension
{
public static DateTime ConvertBetweenTimeZones(this DateTime d, string sourceTimeZone, string destinationTimeZone)
{
var tziSource = TimeZoneInfo.FindSystemTimeZoneById(sourceTimeZone);
var tziDestination = TimeZoneInfo.FindSystemTimeZoneById(destinationTimeZone);
var utcDate = TimeZoneInfo.ConvertTimeToUtc(d, tziSource);
return TimeZoneInfo.ConvertTimeFromUtc(utcDate, tziDestination);
}
}
And some unit test for that:
[TestClass]
public class DateTimeTests
{
[TestMethod]
public void ConvertBetweenTimeZonesTest()
{
var dateTime = new DateTime(2023, 1, 27, 21, 0, 0);
var sourceTimeZone = "Central European Standard Time";
var destTimeZone = "UTC-02";
var dateResult = dateTime.ConvertBetweenTimeZones(sourceTimeZone, destTimeZone);
var expectedDate = new DateTime(2023, 1, 27, 18, 0, 0);
Assert.AreEqual(expectedDate, dateResult);
}
}
[TestClass]
public class TimeZoneInfoTests
{
[TestMethod]
public void ConvertBetweenTimeZonesTest()
{
var timeZone = "Central European Standard Time";
var tzi = TimeZoneInfo.FindSystemTimeZoneById(timeZone);
Assert.AreEqual("UTC+01:00", tzi.GetShortName());
}
}

Check if daylight savings is in effect?

How to check if in Denmark daylight time savings has taken effect, if so, then add 1 hour to my data, else not?
I have a xml file:
<day = "1"
month = "5"
sunrise ="06:30"
sunset ="21:30"
/>
Think you need convert this xml to DateTime and then use TimeZoneInfo class.
If Denmark your local time:
DateTime thisTime = DateTime.Now;
bool isDaylight = TimeZoneInfo.Local.IsDaylightSavingTime(thisTime);
Else you need to get Denmark TimeZone:
DateTime thisTime = DateTime.Now;
// get Denmark Standard Time zone - not sure about that
TimeZoneInfo tst = TimeZoneInfo.FindSystemTimeZoneById("Denmark Standard Time");
bool isDaylight = tst.IsDaylightSavingTime(thisTime);
When I coded as above - for New-York, I found in the debugger that the time was set correctly (including DST)
TimeZoneInfo nyTimeZone = TimeZoneInfo.FindSystemTimeZoneById("Eastern Standard Time");
DateTime nyTime = GetLocalDateTime(DateTime.UtcNow, nyTimeZone);
if (nyTimeZone.IsDaylightSavingTime(nyTime))
nyTime = nyTime.AddHours(1);
public static DateTime GetLocalDateTime(DateTime utcDateTime, TimeZoneInfo timeZone)
{
utcDateTime = DateTime.SpecifyKind(utcDateTime, DateTimeKind.Utc);
DateTime time = TimeZoneInfo.ConvertTime(utcDateTime, timeZone);
return time;
}
You can use TimeZoneInfo.IsDaylightSavingTime
DateTime theDate = new DateTime(2012, 5, 1); // may 1st
TimeZoneInfo tzi = TimeZoneInfo.FindSystemTimeZoneById("Central European Standard Time");
bool isCurrentlyDaylightSavings = tzi.IsDaylightSavingTime(theDate);
Here is a generic test and happy to be corrected if my math is incorrect. In my case I just needed to get the GMT offset for the timezone regardless of where it was in the world.
int timezone;
TimeZoneInfo localZone = TimeZoneInfo.Local;
DateTime myTime = DateTime.Now;
bool isDayLight = TimeZoneInfo.Local.IsDaylightSavingTime(myTime);
if (isDayLight)
timezone = Math.Abs(localZone.BaseUtcOffset.Hours) + 1;
else
timezone = Math.Abs(localZone.BaseUtcOffset.Hours);
Debug.WriteLine("timezone is " + timezone);
I simply found the current time and if it was in Day Light Savings period added +1 to the GMT offset.
This works with Visual Studio Express 2013.
You need to do two things:
call IsAmbiguous
List item IsDaylightSavingTime.
if (TimeZoneInfo.Local.IsAmbiguousTime(unclearDate) ||
TimeZoneInfo.Local.IsDaylightSavingTime(unclearDate))
Console.WriteLine("{0} may be daylight saving time in {1}.", unclearDate, TimeZoneInfo.Local.DisplayName);
https://msdn.microsoft.com/en-us/library/bb460642(v=vs.110).aspx
this is my short solution which can be using in all timezones:
DateTime utcTime = DateTime.Parse("30.10.2018 18:21:34")
DateTime localtime = ConvertUTCToLocalTime(utcTime);
public static DateTime ConvertUTCToLocalTime(DateTime UTCTime)
{
var localZone = TimeZone.CurrentTimeZone;
var offset = localZone.GetUtcOffset(UTCTime);
var localTime = UTCTime.AddHours(offset.Hours);
return localTime;
}
Important
myDateTime.IsDaylightSavingTime DOES return the proper value... but... it is accurate down to at least the hour of the day, just passing the date alone isn't enough.
For instance this year (2019) 3/10/2019 02:00:00 passed as myDateTime will return false, but 3/10/2019 03:00:00 will return true.
Based on other codes provided above, I made a complete code to run and make tests. The variable cityTz is receiving an IANA timezone name example. IANA timezone pattern is used in Mac and Linux (Windows uses different timezone style). In 2020, daylight-saving (DST) in New York ends on November 01. If you test the code below, the return will be FALSE, because "theDate" is November 02, the next day after the end of DST. But if you change the line commented and set theDate to November 01 (last DST date in NY), the return will be TRUE.
You can compile this program in Mac or Linux terminal typing:
csc testDST.cs
To run your program:
mono testDST.exe
Complete code:
using System;
using System.Collections.Generic;
using System.Linq;
class Program{
static void Main(string[] args)
{
string cityTz;
//cityTz = "America/Sao_Paulo";
cityTz = "America/New_York";
//DateTime theDate = new DateTime(2020, 11, 1); //returns TRUE
DateTime theDate = new DateTime(2020, 11, 2); //returns FALSE
Console.WriteLine("Data: "+theDate);
TimeZoneInfo tzi = TimeZoneInfo.FindSystemTimeZoneById(cityTz);
bool isDaylight = tzi.IsDaylightSavingTime(theDate);
Console.WriteLine("isDaylight this date in "+ cityTz +"?: "+ isDaylight);
}
}

Convert UTC DateTime to another Time Zone

I have a UTC DateTime value coming from a database record. I also have a user-specified time zone (an instance of TimeZoneInfo). How do I convert that UTC DateTime to the user's local time zone? Also, how do I determine if the user-specified time zone is currently observing DST? I'm using .NET 3.5.
Thanks,
Mark
The best way to do this is simply to use TimeZoneInfo.ConvertTimeFromUtc.
// you said you had these already
DateTime utc = new DateTime(2014, 6, 4, 12, 34, 0);
TimeZoneInfo tzi = TimeZoneInfo.FindSystemTimeZoneById("Pacific Standard Time");
// it's a simple one-liner
DateTime pacific = TimeZoneInfo.ConvertTimeFromUtc(utc, tzi);
The only catch is that the incoming DateTime value may not have the DateTimeKind.Local kind. It must either be Utc, or Unspecified.
You can use a dedicated function within TimeZoneInfo if you want to convert a DateTimeOffset into another DateTimeOffset:
DateTimeOffset newTime = TimeZoneInfo.ConvertTime(
DateTimeOffset.UtcNow,
TimeZoneInfo.FindSystemTimeZoneById("Eastern Standard Time")
);
Have a look at the DateTimeOffset structure:
// user-specified time zone
TimeZoneInfo southPole =
TimeZoneInfo.FindSystemTimeZoneById("Antarctica/South Pole Standard Time");
// an UTC DateTime
DateTime utcTime = new DateTime(2007, 07, 12, 06, 32, 00, DateTimeKind.Utc);
// DateTime with offset
DateTimeOffset dateAndOffset =
new DateTimeOffset(utcTime, southPole.GetUtcOffset(utcTime));
Console.WriteLine(dateAndOffset);
For DST see the TimeZoneInfo.IsDaylightSavingTime method.
bool isDst = southpole.IsDaylightSavingTime(DateTime.UtcNow);
The Antartica answer only works for the timezones matching UTC. I'm quite traumatized with this DateTimeOffset function and after hours of trial and error, I've managed to produce a practical conversion extension function that works with all timezones.
static public class DateTimeFunctions
{
static public DateTimeOffset ConvertUtcTimeToTimeZone(this DateTime dateTime, string toTimeZoneDesc)
{
if (dateTime.Kind != DateTimeKind.Utc) throw new Exception("dateTime needs to have Kind property set to Utc");
var toUtcOffset = TimeZoneInfo.FindSystemTimeZoneById(toTimeZoneDesc).GetUtcOffset(dateTime);
var convertedTime = DateTime.SpecifyKind(dateTime.Add(toUtcOffset), DateTimeKind.Unspecified);
return new DateTimeOffset(convertedTime, toUtcOffset);
}
}
Example:
var currentTimeInPacificTime = DateTime.UtcNow.ConvertUtcTimeToTimeZone("Pacific Standard Time");
Here's another gotcha: If you're running your code on a Linux server, you need to use the Linux system for timezone names. For example, "Central Standard Time" would be "America/Chicago". The tz list is here: https://en.wikipedia.org/wiki/List_of_tz_database_time_zones
Here's an example with the isWindows switch:
public static class DateTimeHelper
{
public static string ConvertUtcToCst(this string dateTimeString)
{
if (string.IsNullOrWhiteSpace(dateTimeString))
{
return string.Empty;
}
if (DateTime.TryParse(dateTimeString, out DateTime outputDateTime))
{
try
{
var isWindows = RuntimeInformation.IsOSPlatform(OSPlatform.Windows);
TimeZoneInfo cstZone = null;
if (isWindows)
{
cstZone = TimeZoneInfo.FindSystemTimeZoneById("Central Standard Time");
}
else
{
cstZone = TimeZoneInfo.FindSystemTimeZoneById("America/Chicago");
}
var cstDateTime = TimeZoneInfo.ConvertTimeFromUtc(outputDateTime, cstZone);
return cstDateTime.ToString();
}
catch (TimeZoneNotFoundException)
{
return "The registry does not define the Central Standard Time zone.";
}
catch (InvalidTimeZoneException)
{
return "Registry data on the Central Standard Time zone has been corrupted.";
}
catch (Exception ex)
{
return $"Error :: {ex.Message} :: {ex.ToString()}";
}
}
return string.Empty;
}
}
// TO get Currrent Time in current Time Zone of your System
var dt = DateTime.Now;
Console.WriteLine(dt);
// Display Time Zone of your System
Console.WriteLine(TimeZoneInfo.Local);
// Convert Current Date Time to UTC Date Time
var utc = TimeZoneInfo.ConvertTimeToUtc(dt, TimeZoneInfo.Local);
Console.WriteLine(utc);
// Convert UTC Time to Current Time Zone
DateTime pacific = TimeZoneInfo.ConvertTimeFromUtc(utc, TimeZoneInfo.Local);
Console.WriteLine(pacific);
Console.ReadLine();

Categories