TimeZoneInfo类的使用

时间:2020-03-26
本文章向大家介绍TimeZoneInfo类的使用,主要包括TimeZoneInfo类的使用使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

TimeZoneInfo 类的使用

对于一个开放于全球的网站或服务,在时间上的显示是一个问题,因为各个国家都会有所谓的时差,好在 .Net Framework 提供 TimeZoneInfo 类来解决这个问题。

TimeZoneInfo 的使用很简单,一开始利用 FindSystemTimeZoneById 找到对应的 TimeZoneInfo 对象,就可以利用该对象来转换时间。

下列程序是示范如何将 UTC Time 转为东京的当地间时。

           TimeZoneInfo timeZoneInfo = TimeZoneInfo.FindSystemTimeZoneById("Tokyo Standard Time");

            Console.WriteLine(string.Format("UTC Time:{0}", time.ToString()));
            Console.WriteLine(string.Format("Tokyo Time:{0}", TimeZoneInfo.ConvertTime(time, TimeZoneInfo.Utc, timeZoneInfo)));

或许有人会问,该如何知道各个地区所对应的 id,其实利用 TimeZoneInfo.GetSystemtimeZones 就可以了。

 {
                Console.WriteLine(timeZoneInfo.DisplayName);
                Console.WriteLine(timeZoneInfo.Id);
 }

   var ChTimeZone = TimeZoneInfo.FindSystemTimeZoneById("China Standard Time");

   //运行出来就是当地(China Standard Time)时间Datetime.Now
   DateTime ChTime = TimeZoneInfo.ConvertTime(DateTime.Now, TimeZoneInfo.Local, ChTimeZone);

原文地址:https://www.cnblogs.com/ZkbFighting/p/12574338.html