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);
}
}
Related
I have a variable with date time which I have to set on a specific date by these rukles and scenarios:
The API that I connect to has a daily limit and once that limit is reached I have to wait until NEXT DAY until 9:10 AM CEST <= This is very important
So I've been simply doing this:
var localTime = TimeZoneInfo.ConvertTime(DateTime.Now, TimeZoneInfo.FindSystemTimeZoneById("Central European Standard Time"));
var tomorrowAt0910 = localTime.AddDays(1).Date + new TimeSpan(9, 10, 0);
And I have realized that this code has a bug, because I can have following scenarios:
Let's say my application would expire on 30th of July at 15:00 PM in which case this logic up there would be VALID
BUT
We have a next following scenario which is more likely to happen:
Application expires on 31st of July 5:00 AM, in which case this logic is faulty because RENEWAL DATE will be set to 1st of August 9:10AM WHICH IS BAD
If the application expires in this second case, I should set the date to same day and few hours difference (from 5AM to 9AM)
How could I do this?
It sounds like what you really want is to say:
Find the current time in Central Europe
Find 9:10am on the same date
If 9:10am is after the current time, add a day
So something like:
// No need to do this more than once
private static readonly TimeZoneInfo centralEuropeZone =
TimeZoneInfo.FindSystemTimeZoneById("Central European Standard Time")
private static DateTime GetUtcResetTime()
{
// Using UtcNow to make it clear that the system time zone is irrelevant
var centralEuropeNow = TimeZoneInfo.ConvertTime(DateTime.UtcNow, centralEuropeZone);
var centralEuropeResetTime = centralEuropeNow.Date + new TimeSpan(9, 10, 0);
if (centralEuropeResetTime <= centralEuropeNow)
{
centralEuropeResetTime = centralEuropeResetTime.AddDays(1);
}
return TimeZoneInfo.ConvertTimeToUtc(centralEuropeResetTime, centralEuropeZone);
}
I've made that return a UTC DateTime so that no other code needs to worry about which zone it's in.
Check if the expire date is less that the current date, if so add one day.
DateTime expireDate = new DateTime(2018, 7, 30, 22, 0, 0); //for testing
DateTime tomorrowAt0910 = DateTime.Now.Date.AddHours(9).AddMinutes(10);
if (expireDate.Date < DateTime.Now.Date)
{
tomorrowAt0910.AddDays(1);
}
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());
}
}
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.
I'm facing an issue while converting dates between my server and client where both is running in Germany. The Regional settings on the client machines could be set to both UK or Germany.I recieve a date from the server which is CET format, and I need to represent this time on UI as UK time. For example a time recieved from server like say, 01/07/2010 01:00:00 should be represented on the UI as 01/07/2010 00:00:00. I have written a converter for this purpose, however while running it 'am getting a time difference of 2 hours.Below is the code, please can you help?
public class LocalToGmtConverter : IDateConverter
{
private readonly TimeZoneInfo timeZoneInfo;
public LocalToGmtConverter()
: this(TimeZoneInfo.Local)
{
}
public LocalToGmtConverter(TimeZoneInfo timeZoneInfo)
{
this.timeZoneInfo = timeZoneInfo;
}
public DateTime Convert(DateTime localDate)
{
var utcKind = DateTime.SpecifyKind(localDate, DateTimeKind.Utc);
return utcKind;
}
public DateTime ConvertBack(object fromServer)
{
DateTime serverDate = (DateTime)fromServer;
var utcOffset = timeZoneInfo.GetUtcOffset(serverDate);
var uiTime = serverDate- utcOffset;
return uiTime;
}
}
I think you're converting to UTC (instead of UK) time. Since there is still summer time in Central Europe (event if the temperatures say otherwise), the difference is +2 hours until October, 31st.
If you know that you're converting from Germany to UK (i.e. CEST to BST in summer and CET to GMT in winter), why you don't just subtract 1 hour?
If you want the time zone information for UK, you can construct it using
var britishZone = TimeZoneInfo.FindSystemTimeZoneById("GMT Standard Time");
Then you could convert the date using
var newDate = TimeZoneInfo.ConvertTime(serverDate, TimeZoneInfo.Local, britishZone);
This is what I do:
var BritishZone = TimeZoneInfo.FindSystemTimeZoneById("GMT Standard Time");
DateTime dt = DateTime.SpecifyKind(DateTime.UtcNow, DateTimeKind.Unspecified);
DateTime DateTimeInBritishLocal = TimeZoneInfo.ConvertTime(dt, TimeZoneInfo.Utc, BritishZone);
I needed to add the SpecifyKind part or the ConvertTime throws an exception
Use TimeZoneInfo.ConvertTime to convert original input timezone (CET) to target timezone (UK).
public static DateTime ConvertTime(
DateTime dateTime,
TimeZoneInfo sourceTimeZone,
TimeZoneInfo destinationTimeZone
)
Full guidance on MSDN here:
Converting Times Between Time Zones
Modified code sample from MSDN:
DateTime ceTime = new DateTime(2007, 02, 01, 08, 00, 00);
try
{
TimeZoneInfo ceZone = TimeZoneInfo.FindSystemTimeZoneById("Central Europe Standard Time");
TimeZoneInfo gmtZone = TimeZoneInfo.FindSystemTimeZoneById("GMT Standard Time");
Console.WriteLine("{0} {1} is {2} GMT time.",
ceTime,
ceZone.IsDaylightSavingTime(ceTime) ? ceZone.DaylightName : ceZone.StandardName,
TimeZoneInfo.ConvertTime(ceTime, ceZone, gmtZone));
}
catch (TimeZoneNotFoundException)
{
Console.WriteLine("The registry does not define the required timezones.");
}
catch (InvalidTimeZoneException)
{
Console.WriteLine("Registry data on the required timezones has been corrupted.");
}
The better approach to deal with local times is store them in unified representation such as UTC.
So you can convert all input times to UTC (via .ToUniversalTime()), and store (or transmit) its value. When you need to show it just convert back by using .ToLocalTime().
So you avoid rquirements to know which time zone was original value and can easily show stored value in different timezones.
Also you can avoid incoming troubles where you have to write specific logic for processing time in next timezone trying to figure out how to convert them amongs all available.
I realize the question is for C#, but if all you want to do is a single conversion you can do this from the PowerShell command line:
$d = [DateTime]::Parse("04/02/2014 17:00:00")
$gmt = [TimeZoneInfo]::FindSystemTimeZoneById("GMT Standard Time");
[TimeZoneInfo]::ConvertTime($d, $gmt, [TimeZoneInfo]::Local)
This script would convert 17:00 UK time into your local time zone.
For me, that would be CST. It's interesting to note that if I had set the date to 03/27/2014, the result would be different because the UK daylight saving time kicks in on different dates that the US.
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();