Change timezone in C#

11,027

Solution 1

I guess you have to go the old road of understanding timezones. Your example is though pretty easy.

GMT is UTC with daylight saving changes.
EST is UTC -5hrs with daylight saving changes.

So you just have to substract 5 hours to get the time in EST.

Solution 2

For Net 2.0 and 1.1 you could use the TimeZone class which has now been replaced by the TimeZoneInfo class.

Edit after further research It would appear that prior to NET 3.5 all that was available was the TimeZone class. It is not possible to calculate the TimeDate value for timezones other than the local one and UTC. So if you wish to calculate the time as EST or PST and you're based in the UK then things become a little more difficult.

Here's a short demo program for using TimeZone (its from a basic console app.:

class Program
{
    static void Main(string[] args)
    {
        DateTime time = DateTime.UtcNow;
        Console.WriteLine(string.Format("UTC time is {0}", time.ToShortTimeString()));

        TimeZone zone = TimeZone.CurrentTimeZone;

        //The following line depends on a call to TimeZone.GetUtcOffset for NET 1.0 and 1.1
        DateTime workingTime = zone.ToLocalTime(time);
        DisplayTime(workingTime, zone);
        IFormatProvider culture = new System.Globalization.CultureInfo("en-GB", true);
        workingTime = DateTime.Parse("22/2/2010 12:15:32");

        Console.WriteLine();
        Console.WriteLine(string.Format("Historical Date Time is : {0}",workingTime.ToString()));
        DisplayTime(workingTime, zone);
        Console.WriteLine("Press any key to close ...");
        Console.ReadLine();
    }
    static void DisplayTime(DateTime time, TimeZone zone)
    {
        Console.WriteLine(string.Format("Current time zone is {0}", zone.StandardName));
        Console.WriteLine(string.Format("Does this time include Daylight saving? - {0}", zone.IsDaylightSavingTime(time) ? "Yes" : "No"));
        if (zone.IsDaylightSavingTime(time))
        {
            Console.WriteLine(string.Format("So this time locally is {0} {1}", time.ToShortTimeString(), zone.DaylightName));
        }
        else
        {
            Console.WriteLine(string.Format("So this time locally is {0} {1}", time.ToShortTimeString(), zone.StandardName));
        }
        Console.WriteLine(string.Format("Time offset from UTC is {0} hours.", zone.GetUtcOffset(time)));

    }
}

As you can see it only deals with local time and UTC.

Share:
11,027
Leon Lang
Author by

Leon Lang

:-)

Updated on June 04, 2022

Comments

  • Leon Lang
    Leon Lang almost 2 years

    I have a date format, something similar to:

    Mon, Sun, 22 Aug 2010 12:38:33 GMT

    How do I convert this to EST format?

    Note: I know it can be achieved using TimeZoneinfo, but that is introduced in 3.5, i want to do it 2.0 or any old version.