Change timezone in C #

I have a date format, something similar to:

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

How to convert this to EST format?

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

+3
source share
4 answers

I think you need to follow the old road of understanding time zones. Your example is pretty simple.

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

So, you just need to subtract 5 hours to get the time in EST.

+3
source

, , , 5 , .

DateTime dateTime = DateTime.UtcNow;
dateTime.AddHours(-5);

.. .

+1

Net 2.0 1.1 TimeZone, TimeZoneInfo.

, NET 3.5 , , TimeZone. TimeDate , UTC. , EST PST, , .

TimeZone ( .

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)));

    }
}

, UTC.

+1

EST is probably not a format, but an abbreviation of the time zone. That is, a “manual” method would be to analyze the above date and subtract the difference in time zones. You should beware of summer time, that is, you need to check whether the above time corresponds to summer time or not.

0
source

Source: https://habr.com/ru/post/1761086/


All Articles