提问者:小点点

如何从Utc日期时间对象和时区偏移值中获取时区信息


给定一个UTC的日期时间(参见下面的utc变量)和一个timezone Offset值(参见下面的timezoneOffsetMilliByds变量),如何获取原始用户日期时间输入的时区信息?

我正在做什么和想做更多的细节:

var originalUserInput = DateTime.Now; // got from user input as original input.

decimal timezoneOffsetMilliSeconds = 18000000; // Example: "Central Standard Time" time zone off set. Got from user input.

var utc = originalUserInput .AddMilliseconds((double)timezoneOffsetMilliSeconds); // convert to UTC date time to store into database.

var backToUserInput = utc.AddMilliseconds((double)-timezoneOffsetMilliSeconds);  // got from database for UTC date time and convert it back to original user input

我的问题:如何从数据库存储的utc和存储的timezoneOffsetMilli秒值中获取用户的时区信息(例如中央标准时间、CST等)?

谢谢你们


共1个答案

匿名用户

如果这是本地应用程序而不是Web应用程序,您可以执行以下操作。

选项1:存储偏移量

var currentLocalTime = DateTime.Now; // or whatever user time input is

var currentUTCTime = currentLocalTime.ToUniversalTime(); // store utc time in db
var utcOffset = (currentLocalTime - currentUTCTime).Hours; //store utc offset in db

var utcTimeFormattedToLocalTime = currentUTCTime.AddHours(utcOffset); //recalculate the local time from db fields

输出如下:

Local Time: 8/6/2022 3:36:46 PM
UTC Time: 8/6/2022 8:36:46 PM
Offset: -5
Recalculated Local Time From UTC with Offset: 8/6/2022 3:36:46 PM

选项2:根据正在运行代码的机器将UTC转换为本地时间

var userInputDate = DateTime.Now; //or whatever the user inputs
var utcDate = userInputDate.ToUniversalTime(); //save to DB

var localTime = utcDate.ToLocalTime(); // this will convert to users local time based on their machines timezones, or wherever the code is ran.

输出:

Local Time: 8/6/2022 3:37:44 PM
UTC Time: 8/6/2022 8:37:44 PM

备选方案3:

获取偏移量,然后使用它根据本地机器或代码运行的位置进行计算。

var offset = TimeZoneInfo.Local.GetUtcOffset(DateTime.UtcNow);

您可以在DB存储的UTC值上使用偏移量,如果您不想存储偏移量,则不必存储偏移量。

如果这是一个Web应用程序,您需要以不同的方式做事,但您没有在OP中指定。如果是这样,请评论。

如果您想要用户Timezone信息,您可以使用TimeZoneInfo类。

你可以这样做:

var tz = TimeZoneInfo.Local;

这将返回您这个:

您可以在变量“tz”上打点以获得标准时间。

tz.标准名称=中央标准时间