Hello Techies,
Today we are going to create two functions that make your life easy and handle different times and make your application or web completely dynamic within different time zones.
Overview
In this internet world, we don't have any idea which person is accessing our application from which country, and our application doesn't have any idea about the time duration in the device and because of that issue sometimes our application is going to crash or giving an unreliable result to the user. So, we have to handle the different times for different countries.
What is Time Zone?
The Time Zone has some parameters, one is offset, or we can say a difference between two times in an hour, which you can see in the times for different countries. Let's say right now in India the current time is 12:59 AM then at the same time in Canada the time is 2:29 AM. so, we can see the difference in the time is defined by the Time Zone
Now, the question is how does this Time Zone show the difference with different countries, Rrght?
So, every country has its own time difference compared to other countries. Like we compare Indian time zone with Canadian time zone where India is 10 hours and 30 minutes ahead of Ottawa for example.
Now, to show this difference there is a universal timezone which is global timezone that shows the difference in terms of the hours and minute. So, when we compare Indian time with the UTC where India is 5 hours and 30 minutes ahead of Coordinated Universal Time and UTC time with Canadian where Coordinated Universal Time is 5 hours ahead of Ottawa. Ultimately it becomes the 10 hours and 30 minutes,
Now, let's check how it shows the difference, for example, Indian UTC timezone is UTC+05:30 and Canadian UTC timezone is UTC-05:30. So, here values like the +5:30 and -5:30 are called the offset, and it adds or subtract the hours:minutes based on your conversion with reference to UTC.
Requirement
For this solution, we need to import one package into our project which is TimeZoneConverter.
Which we can install directly from the NuGet package manager window or package manager console.
- To install it with the help of NuGet Package manager, Go To Tools → NuGet Package Manager → Manage NuGet Packages for Solution. And then search the TimeZoneConverter in Browse tab and install it.
- To install it with the help of Package Manager Console, Go To Tools → NuGet Package Manager → Package Manager Console and copy the following command and paste it inside the console and install it.
Install-Package TimeZoneConverter
OR
Install-Package TimeZoneConverter -Version 5.0.0
I have added two commands, one is with the -Version <version number parameter> which is optional if you want to install it with the specific version, and if you want to install the latest package then you can use the first command.
Solution
Now, let's quickly move on to our solution and what we are going to do over here is we are going to take a current time zone and time and with respect to the timezone we are going to convert it to the UTC time zone to store the time in the database, and we are going to perform the operation on the UTC time zone and at the time of getting the data from the database we are again going to convert it to the current time with respect to timezone.
Convert to UTC with Specific Time Zone
Currently, we are using the c# for this function, and we can use it as a library as well.
localDateTime = DateTime.SpecifyKind(localDateTime, DateTimeKind.Unspecified)
This method is used to create a new DateTime object which has the same number of ticks as the specified DateTime but is designated as either local time, Coordinated Universal Time (UTC), or neither, as indicated by the specified DateTimeKind value.
Over here, we have specified this date time as unspecified because we have a timezone we want to convert it to the UTC time with respect to the timezone which we have. So, we have to mark the kind as unspecified.
NOTE: Mostly the Developer uses the ToUnivesalTime() function to convert time to UTC, but it results in inconsistent output if timezone is not same, which basically takes deployed environment's timezone as reference.
DateTime localDateTime = DateTime.SpecifyKind(localDateTime, DateTimeKind.Unspecified);
TimeZoneInfo ut = TimeZoneInfo.FindSystemTimeZoneById(TZConvert.IanaToWindows(timezone));
Now, we have unspecified the kind, and we are moving towards getting our windows type time zone. So, firstly, let's just narrow down the above code to understand more about the conversion functions.
TZConvert.IanaToWindows(timeZone)
The above code is from the package which we have imported and what it does is we have a database of the different type of the timezone from one there is a IANA/Olson Time Zone Database. For more information about the different timezone type, you can visit Different Time Zone Database.
So, we are using this IANA Database, so it stores the time zone as "America/New_York" for example, and we require something like this "Eastern Standard Time" which is used to convert by our c# functions.
So, we are using this function to translate the IANA time zone to our windows type, and it returns the string which is of windows time timezone.
var WindowsTimeZone=TZConvert.IanaToWindows(timeZone);
TimeZoneInfo ut=TimeZoneInfo.FindSystemTimeZoneById(WindowsTimeZone);
Now, the first line is the same to convert IANA timezone to windows and store to variable.
Now the TimeZoneInfo. FineSystemTimeZoneById is taking the windows type timezone as argument and matches it with the local system's key and returns an object of the information about the offset, current time and many more information. Which can be used by the other functions.
In short, this functions returns us information about the windows type timezone by key which we have passed as argument.
var WindowsTimeZone=TZConvert.IanaToWindows(timeZone);
TimeZoneInfo ut=TimeZoneInfo.FindSystemTimeZoneById(WindowsTimeZone);
DateTime localDateTime = TimeZoneInfo.ConvertTimeToUtc(localDateTime, ut);
Now, the line 3 in the above code "TimeZoneInfo. ConvertTimeToUtc" is going to take the windows type timezone object and take the necessary information about the timezone like the Offset and add/subtract it with the localDateTime and returns us a date which is in the UTC with respect to the timezone which we have specified as second argument.
Now, let's just create a function for that, which takes the date time and timezone and returns us a time in UTC with respect to the specified timezone.
public static DateTime ConvertLocalToUTCwithTimeZone(DateTime localDateTime,string timezone)
{
localDateTime = DateTime.SpecifyKind(localDateTime, DateTimeKind.Unspecified);
TimeZoneInfo ut = TimeZoneInfo.FindSystemTimeZoneById(TZConvert.IanaToWindows(timezone));
return TimeZoneInfo.ConvertTimeToUtc(localDateTime, ut);
}
UTC To Specific Time Zone
Now, we have checked with the functions which returns us the UTC date time with respect to the Time Zone but now what if we want to get the date time from the UTC with respect to the timezone. So, let's check out the following code:
var WindowsTypeTimeZone = TZConvert.IanaToWindows(timeZone);
var TimeZoneInfo=TimeZoneInfo.FindSystemTimeZoneById(WindowsTypeTimeZone);
TimeZoneInfo.ConvertTimeFromUtc(Date,TimeZoneInfo);
Now, As we have already checked, the code which returns us the UTC time. So, as per that, we have a code to get the date time for specific timezone from UTC is similar to that.
On First line, we are translating the IANA type timezone to windows type timezone.
In the second line, we are getting the information about the windows type timezone.
Now in the third line we have directly converted the UTC Date time to particular date time with respect to the timezone which we have specified.
NOTE : To Convert time From UTC we have not specified any kind as we know this is the UTC date time from which we have to convert to specific timezone.
Let's just create a function for the same, which we can reuse in our project.
public static DateTime getLocaltimeFromUniversal(DateTime utcDateTime, string timeZone)
{
return TimeZoneInfo.ConvertTimeFromUtc(utcDateTime,
TimeZoneInfo.FindSystemTimeZoneById(TZConvert.IanaToWindows(timeZone)));
}
Convert DateTime to Specific Time Zone
Now, If we want to convert time to specific time, we can reuse both function and create a new function which directly returns you the time of the specific timezone from the particular timezone of time.
Let's say, I have a time in IST and I don't want to handle this different time in the code and want the single function call which returns me the time of specific time.
public static DateTime GetTimeofTimeZone(localDateTime,FromTimeZone,ToTimeZone)
{
DateTime utcTime=ConvertLocalToUTCwithTimeZone(localDateTime,FromTimeZone);
return getLocaltimeFromUniversal(utcTime,ToTimeZone);
}
Now, What the above function does is taking the three arguments on is the DateTime which you want to convert, the timezone of the date time, and third is the time zone in which you convert your date time.
To Calculate all this,
- First we call the function to get UTC time with time zone and date we got
- Secondly, we will call the function to local time with the UTC date which got from the first function call and timezone in which we want to convert
- in result, it returns me the date time in resultant time zone.
Create Class For Class Library
Now, If we want to make it as the class library, and then we have to reuse in the different projects then you can use the following class and import as the class library and debug it and prepare a DLL of it, and you can import that DLL and reuse it in your different projects.
using System;
using TimeZoneConverter;
namespace TimeZoneHelper
{
public static class TimezoneHelper
{
public static DateTime getLocaltimeFromUniversal(DateTime utcDateTime, string timeZone)
{
return TimeZoneInfo.ConvertTimeFromUtc(utcDateTime,
TimeZoneInfo.FindSystemTimeZoneById(TZConvert.IanaToWindows(timeZone)));
}
public static DateTime ConvertLocalToUTCwithTimeZone(DateTime localDateTime,string timezone)
{
localDateTime = DateTime.SpecifyKind(localDateTime, DateTimeKind.Unspecified);
return TimeZoneInfo.ConvertTimeToUtc(localDateTime,
TimeZoneInfo.FindSystemTimeZoneById(TZConvert.IanaToWindows(timezone)));
}
}
}
I also have attached one zip file with this Article, which contains the above class file and one DLL file. A DLL file is a class library file which you can use with different project as reference.
I hope this is helpful to you, for you to make your application dynamic.