Time zone conversion in C#

前端 未结 2 703
既然无缘
既然无缘 2021-01-21 15:59

I have a date format, something similar to:

Mon, 11 Aug 2009 13:15:10 GMT

How do I convert this to EST format?

2条回答
  •  清歌不尽
    2021-01-21 17:05

    This, or similar should do the trick:

    var dateString = "Tue, 11 Aug 2009 13:15:10 GMT";
    var date = Convert.ToDateTime(dateString);
    var result = TimeZoneInfo.ConvertTime(date, TimeZoneInfo.FindSystemTimeZoneById("Eastern Standard Time"));
    

    It's worth mentioning, that your originally specified Mon, 11 Aug 2009, is actually incorrect, hence I've changed it to Tue, 11 Aug 2009 so the code will run, as the Convert.ToDateTime throws an exception if the day does not match the date.

    I've also assumed that you mean Eastern Standard Time, which is the id associated with "Eastern Time (US & Canada)", but you can get a full list of the time zones available by running the following code:

    foreach(TimeZoneInfo info in TimeZoneInfo.GetSystemTimeZones())
    {
        Console.WriteLine("Id: {0}", info.Id);
        Console.WriteLine("   DisplayName: {0}", info.DisplayName);
    }
    

提交回复
热议问题