[英]Change timezone in C#
我有一個日期格式,類似於:
周一,周日,2010年8月22日12:38:33 GMT
如何將其轉換為EST格式?
注意:我知道它可以使用TimeZoneinfo實現,但是在3.5中引入,我想要做2.0或任何舊版本。
最簡單的方法可能是花費5個小時的時間。
DateTime dateTime = DateTime.UtcNow;
dateTime.AddHours(-5);
但這不能解釋夏令時等問題。但是你可以隨時編寫這種可能性的代碼。
對於Net 2.0和1.1,您可以使用TimeZone類,該類現在已被TimeZoneInfo類替換。
進一步研究后編輯看來,在.NET 3.5之前,所有可用的都是TimeZone類。 無法計算本地和UTC之外的時區的TimeDate值。 因此,如果您希望將時間計算為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。
EST可能不是格式,而是時區的縮寫。 即“手動”方式是解析上述日期並減去時區差異。 您應該注意夏令時,即您需要檢查上述時間是否符合夏令時期。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.