TimeZoneInfo是.NET 3.5的新物件
這個類別的說明是表示世界的任意時區,大部分的方法都圍繞在比對UTC時間來判斷系統中其他時區的時間
列出所有FindSystemTimeZoneById的ID
foreach (TimeZoneInfo timeZone in TimeZoneInfo.GetSystemTimeZones())
{
//該時間區域ID
Console.WriteLine(timeZone.Id);
//區域名稱
Console.WriteLine(timeZone.StandardName);
//與世界標準時間差
Console.WriteLine(timeZone.BaseUtcOffset.ToString());
//該時間區域時間
DateTime CurrentDateTime = DateTime.Now.AddHours(timeZone.BaseUtcOffset.Hours);
Console.WriteLine(CurrentDateTime);
//string timeinfo = timeZone.Id + " " + timeZone.StandardName + " " + timeZone.BaseUtcOffset.ToString() + " " + CurrentDateTime+Environment.NewLine;
//textBox2.Text += timeinfo;
}
將時間換成各地的時間
DateTime timeUtc = DateTime.UtcNow;
try
{
//text="AUS Central Standard Time" 請填入上述找出來的timeZone.id的值
TimeZoneInfo cstZone = TimeZoneInfo.FindSystemTimeZoneById(text);
DateTime cstTime = TimeZoneInfo.ConvertTimeFromUtc(timeUtc, cstZone);
//string showtime = "The date and time are " + cstTime.ToString() + " " + cstZone.IsDaylightSavingTime(cstTime) ? cstZone.DaylightName : cstZone.StandardName;
string daylight;
if (cstZone.IsDaylightSavingTime(cstTime))
{
daylight = cstZone.DaylightName;
}
else
{
daylight = cstZone.StandardName;
}
textBlock1.Text = "The date and time are " + cstTime.ToString() + " " + daylight;
Console.WriteLine("The date and time are {0} {1}.", cstTime,cstZone.IsDaylightSavingTime(cstTime) ?cstZone.DaylightName : cstZone.StandardName);
}
catch (TimeZoneNotFoundException)
{
Console.WriteLine("The registry does not define the Central Standard Time zone.");
}
catch (InvalidTimeZoneException)
{
Console.WriteLine("Registry data on the Central STandard Time zone has been corrupted.");
}
留言列表