How to convert DateTime into different timezones?

前端 未结 4 1532
囚心锁ツ
囚心锁ツ 2021-01-02 04:02

How to convert DateTime into different timezones? The DateTime class has two methods .toLocal() and .toUtc(). But if I want to display time in another time zone. How can I d

4条回答
  •  野趣味
    野趣味 (楼主)
    2021-01-02 04:22

    You can use TimeZoneInfo.ConvertTime() to change timezone. Try like this

    DateTime hwTime = new DateTime(2007, 02, 01, 08, 00, 00);
    try {
        TimeZoneInfo hwZone = TimeZoneInfo.FindSystemTimeZoneById("Hawaiian Standard Time");
        TimeZoneInfo.ConvertTime(hwTime, hwZone, TimeZoneInfo.Local));
    }
    catch (TimeZoneNotFoundException) {
        Console.WriteLine("Timezone not found");
    }                           
    catch (InvalidTimeZoneException) {
        Console.WriteLine("Invalid Timezone");
    }
    

    This will convert from Hawaiian Standard Time to Local.

    It is just an example. Use it to convert as per your need.

提交回复
热议问题