且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在 C# 中将 UTC 日期时间转换为本地日期时间

更新时间:2023-02-03 17:24:51

要将 UTC DateTime 转换为您的 Local DateTime,您必须使用 TimeZoneInfo 如下:

To convert the UTC DateTime to your Local DateTime, you have to use TimeZoneInfo as follows:

DateTime startTimeFormate = x.Startdate; // This  is utc date time
TimeZoneInfo systemTimeZone = TimeZoneInfo.Local;
DateTime localDateTime = TimeZoneInfo.ConvertTimeFromUtc(startTimeFormate, systemTimeZone);

此外,如果您想将 UTC DateTime 转换为用户特定的 Local DateTime,请执行以下操作:

Moreover if you want to convert UTC DateTime to user specific Local DateTime then do as follows:

string userTimeZoneId = "New Zealand Standard Time";
TimeZoneInfo nzTimeZone = TimeZoneInfo.FindSystemTimeZoneById(userTimeZoneId);
DateTime userLocalDateTime = TimeZoneInfo.ConvertTimeFromUtc(utcDateTime, userTimeZoneId);

注意:.NET 中的 TimeZone过时 现已弃用.而是使用 TimeZoneInfo.

Note: TimeZone in .NET is obsolete now and it has been deprecated. Instead use TimeZoneInfo.