在 C# 中将 UTC 日期时间转换为本地日期时间 [英] Converting UTC DateTime to Local DateTime in C#

查看:106
本文介绍了在 C# 中将 UTC 日期时间转换为本地日期时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想显示日期 &将根据用户的时区管理的事件的时间.要检查时区,我将系统时区更改为另一个时区,但我的代码仍在获取本地时区.这是我的代码

I want to show Date & Time of an event which will be managed according to time zone of user. To check time zone I change my system time Zone to another time zone but my code is still getting Local time Zone. Here's My code

我正在使用 Cassendra 数据库和 C# .NET MVC

I am using Cassendra Database and C# .NET MVC

DateTime startTimeFormate = x.Startdate;
DateTime endTimeFormate = x.Enddate;
TimeZone zone = TimeZone.CurrentTimeZone;
DateTime startTime = zone.ToLocalTime(startTimeFormate);
DateTime endTime = zone.ToLocalTime(endTimeFormate);

推荐答案

要将 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.

这篇关于在 C# 中将 UTC 日期时间转换为本地日期时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆