Change timezone in C#
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.
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.
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.
EST is probably not a format but an abbreviation of the time zone. I.e. the "manual" way would be to parse the above date and subtract the time zone difference. You should be beware of daylight saving time periods, i.e. you need to check if the above time fits the DST period or not.
The simplest way would probably be to just take 5 hours off the time like so.
DateTime dateTime = DateTime.UtcNow;
dateTime.AddHours(-5);
But this won't account for daylight savings etc. But you could always code for that possibility.
精彩评论