C#/.NET怎么样将UTC时间转换成美国东部时间(EST)

C#开发 2015-11-05 1872阅读 0评论 0收藏 收藏本文

C#/.NET将UTC时间转换成美国东部时间(EST)时,我们需要使用到.NET Framework中与时区有关的TimeZoneInfo类的静态方法:FindSystemTimeZoneById("时区名称");然后再用TimeZoneInfo的静态方法:TimeZoneInfo.ConvertTimeFromUtc()将UTC时间转换成指定时区中的时间,具体示例代码如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication1
{
  class Program
  {
    static void Main(string[] args)
    {
      TimeZoneInfo easternZone = TimeZoneInfo.FindSystemTimeZoneById("Eastern Standard Time");
      DateTime easternTime = TimeZoneInfo.ConvertTimeFromUtc(DateTime.UtcNow, easternZone);
      Console.WriteLine("Local Time:{0}", DateTime.Now);
      Console.WriteLine("UTC Time:{0}", DateTime.UtcNow);
      Console.WriteLine("EST Time:{0}", easternTime);

      Console.ReadKey();
    }
  }
}
运行结果如下: convert-utc-to-est-01 如果我们还需要将上例转换得到的EST时间格式化成ISO 8601格式的,又应该怎么做呢?答案有很多种,这里列举其中一种,即使用DateTime.ToString()方法,还是把完整的示例代码贴出来:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication1
{
  class Program
  {
    static void Main(string[] args)
    {
      TimeZoneInfo easternZone = TimeZoneInfo.FindSystemTimeZoneById("Eastern Standard Time");
      DateTime easternTime = TimeZoneInfo.ConvertTimeFromUtc(DateTime.UtcNow, easternZone);
      Console.WriteLine("Local Time:{0}", DateTime.Now);
      Console.WriteLine("UTC Time:{0}", DateTime.UtcNow);
      Console.WriteLine("EST Time:{0}", easternTime);

      Console.WriteLine("{0}", easternTime.ToString("yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fff'z'"));

      Console.ReadKey();
    }
  }
}
运行结果如下图: convert-utc-to-est-02  

转载请注明:图享网 » C#/.NET怎么样将UTC时间转换成美国东部时间(EST)

文章评论

获取验证码