Showing posts with label DateTime. Show all posts
Showing posts with label DateTime. Show all posts

Thursday, 12 December 2019

C#.NET - Convert DateTime from Different TimeZones to UTC

/// Takes the date time and the Zone Name of the DateTime and convert to UTC
public static DateTime ConvertSpecifiedZoneDateTimeToUTC(DateTime dateTime, string timeZoneName)
{
  return TimeZoneInfo.ConvertTimeToUtc(dateTime, TimeZoneInfo.FindSystemTimeZoneById(timeZoneName));
}
// How to Use?
DateTime utcDate= ConvertSpecifiedZoneDateTimeToUTC(DateTime.Now, "Central Standard Time")

C# - How to Convert UTC DateTime to Specific Time Zone

/// Converts UTC DateTime to Given Time Zone
public static DateTime ConvertUtcByZone(DateTime utcDateTime, string destinationTimeZoneName)
        {
            utcDateTime = DateTime.SpecifyKind(utcDateTime, DateTimeKind.Unspecified);
            TimeZoneInfo centralZone = TimeZoneInfo.FindSystemTimeZoneById(destinationTimeZoneName);
            return TimeZoneInfo.ConvertTimeFromUtc(utcDateTime, centralZone);
        }

/// How to use?
ConvertUtcByZone(DateTime.UtcNow, "Central Standard Time")

C# - How to get CST to UTC DateTimeOffset?

DateTimeOffset - Gives detailed date and time difference.
/// <summary>
/// Gets the datetime offset difference between the CST to UTC
/// </summary>
/// <returns></returns>
public static DateTimeOffset GetCstToUtcOffset()
{
    TimeZoneInfo cstZone = TimeZoneInfo.FindSystemTimeZoneById("Central Standard Time");
    DateTimeOffset utcOffset = new DateTimeOffset(DateTime.UtcNow, TimeSpan.Zero);
    return utcOffset.ToOffset(cstZone.GetUtcOffset(utcOffset));
}