从 Azure 数据库接收数据后更改 DateTime 以对应用户本地

Change DateTime to correspond user local after receiving data from Azure database

我有一项服务正在将数据写入 Azure 数据库。但是,Azure 会自动以 UTC 格式写入这些“时间戳”。由于我不在 UTC 区,我的时间戳不正确。经过一些调查,我了解到有几种选择。我很难理解我应该使用哪一个?目前很难看到未来可能出现的所有问题。

这是我的模型:

  public class DataRecord : IDataRecord
  {
    public int Id { get; set; }
    public DateTime TimeNow { get; set; }
  }

所以目前 Azure 不关心我在哪个区域,只用 UTC 写这个 DateTime 时间。

可能的选择(我理解)我有:

  1. 将 DateTime 更改为字符串,然后在客户端解析回 DateTime
  2. 将客户端设置添加到 select TimeZone,然后计算 Azure DateTime + 偏移 selected TimeZone。如果是这个解决方案,我应该以哪种格式创建时区列表以及如何执行计算?日期时间格式的 UTC 时间戳 + ?
  3. 自动检索客户端时间,我看到有一些 JavaScript 解决方案可以获取用户浏览器时间。例如:

我的服务,即将数据写入数据库,与客户端处于同一时区。基本上不需要做任何计算。

我的项目结构如下:客户端、服务器、共享

以 UTC 格式存储日期是可取的,因为它是一个标准化的基础,可以使用 Microsoft DateTime 方法轻松计算任何其他区域的时间。

保存数据时,如果您在代码中创建时间戳,则使用:

DateTime myDateTimeToStore = DateTime.UtcNow;

如果数据是由用户输入的(使用他们的本地时区),则将输入捕获到 DateTime,然后转换为 UTC:

DateTime localDateTimeInputByUser;

DateTime utcDateTime = localDateTimeInputByUser.ToUniversalTime();

转换为 Utc 后,您可以存储在数据库中。

然后,在检索时,您可以将其转换回本地时间,使用:

DateTime utcDateTimeFromDatabase;

DateTime localDateTime = utcDateTimeFromDatabase.ToLocalTime();

对于更复杂的情况,您可以在时区之间转换而无需自己进行数学计算:

https://docs.microsoft.com/en-us/dotnet/standard/datetime/converting-between-time-zones

You could have a look on below steps to trigger your requirement.

"Change DateTime into string and then parse back into DateTime on Client side"

完全同意,你可以这样做,像这样并且它按预期工作

Azure Live Example:

        var animal = await _context.Animals.FindAsync(id); // Getting Time From Azure 
        var azureTime = Convert.ToDateTime(animal!.AzureTime); // Because I have save date time as string
        var convertedToLocalTime = azureTime.ToLocalTime(); // Local Time

Output:

Note: Here you might encounter one issue, if your server time is not same as your local time in that case time conversion may not be as expected. So if that is the case you could have a try below way:

Convert Azure Time To Any Standard Time:

这就是您可以将 UTC 时间转换为任何 standard time zone 的方式。这是示例:

        var azureTime = "18-Apr-22 5:21:29 AM"; // Getting Time From Azure 
        var convertedAzureTime = Convert.ToDateTime(azureTime); // Because I have save date time as string
        TimeZoneInfo gmtZone = TimeZoneInfo.FindSystemTimeZoneById("GMT Standard Time");
        DateTime yourLocalTime = TimeZoneInfo.ConvertTimeFromUtc(convertedAzureTime, gmtZone);
        Console.WriteLine("Azure Time {0}",convertedAzureTime);
        Console.WriteLine("Converted Local Time {0}",yourLocalTime);

Note: You can convert in anytime zone you want by using FindSystemTimeZoneById. You can check the dotnetfiddle example here

Output:

希望以上的解​​释和例子能给你相应的指导