ASP.NET Core UTC 时间转本地时间

Ljt*_*Ljt 2 postgresql asp.net-core angular asp.net-core-5.0

我使用 ASP.NET Core 5 和 Entity Framework Core 作为我的 ORM。我从 Angular 应用程序获取 UTC 时间。但用户将仅来自一个国家。所以我决定将UTC时间转换为本地\xe2\x80\x94i.e印度的时区\xe2\x80\x94,同时保存到数据库。

\n

我的问题:

\n
    \n
  1. 如何将 ASP.NET Core 应用程序配置为en-IN在存储到数据库时始终将 UTC 时间转换为 UTC 时间?
  2. \n
  3. 另外,在将数据发送到 API 时,我需要将本地时间转换回 UTC。
  4. \n
\n

请任何人建议该应用程序当地时间始终为en-IN,但托管在相同/不同的国家/地区。

\n

请告诉我如何将 UTC 时间转换为本地时间(en-IN),反之亦然

\n

Zhi*_* Lv 5

在 asp.net core 中,将时间转换为 UTC 的最简单方法是调用静态(在 Visual Basic 中共享)TimeZoneInfo.ConvertTimeToUtc(DateTime) 方法。

\n
        DateTime dateNow = DateTime.Now;\n\n        Console.WriteLine("Local date and time: " + dateNow);\n\n        var kind = dateNow.Kind;\n        Console.WriteLine("The date and time are {0} UTC.",\n                           TimeZoneInfo.ConvertTimeToUtc(dateNow));\n
Run Code Online (Sandbox Code Playgroud)\n

然后,要将 UTC 转换为您指定的任何时区的时间,请调用 ConvertTimeFromUtc 方法。

\n
        DateTime timeUtc = DateTime.UtcNow;\n        try\n        {\n            TimeZoneInfo cstZone = TimeZoneInfo.FindSystemTimeZoneById("India Standard Time");\n            DateTime cstTime = TimeZoneInfo.ConvertTimeFromUtc(timeUtc, cstZone);\n            Console.WriteLine("The date and time are {0} {1}.",\n                              cstTime,\n                              cstZone.IsDaylightSavingTime(cstTime) ?\n                                      cstZone.DaylightName : cstZone.StandardName);\n        }\n        catch (TimeZoneNotFoundException)\n        {\n            Console.WriteLine("The registry does not define the India Standard Time zone.");\n        }\n        catch (InvalidTimeZoneException)\n        {\n            Console.WriteLine("Registry data on the India Standard Time zone has been corrupted.");\n        }\n
Run Code Online (Sandbox Code Playgroud)\n

更多详细信息,请参阅转换时区之间的时间DateTime.ToUniversalTime 方法(将日期时间字符串转换为 DateTime 对象)。

\n

此外,您还可以使用 JavaScript 在 UTC 时间和本地时间之间转换日期时间。

\n

要使用 JavaScript 将 UTC 时间转换为本地日期时间(具有特定时区),您可以尝试使用Date.prototype.toLocaleString()方法。

\n

示例代码如下:

\n
const event = new Date(Date.UTC(2012, 11, 20, 3, 0, 0));\n\n// British English uses day-month-year order and 24-hour time without AM/PM\nconsole.log(event.toLocaleString(\'en-IN\', { timeZone: \'UTC\' }));\n// expected output: 20/12/2012, 03:00:00\n\n// Korean uses year-month-day order and 12-hour time with AM/PM\nconsole.log(event.toLocaleString(\'ko-KR\', { timeZone: \'UTC\' }));\n// expected output: 2012. 12. 20. \xec\x98\xa4\xec\xa0\x84 3:00:00\n\nconsole.log(\'USA time: \'+ event.toLocaleString("en-US", {timeZone: "America/New_York"}))\n// expected output: USA time: 2020-11-15T13:20:52.000Z \n\nconsole.log(\'India time: \'+ event.toLocaleString("en-US", {timeZone: "Asia/Kolkata"}))\n// expected output: India time: 2020-11-15T23:50:52.000Z\n
Run Code Online (Sandbox Code Playgroud)\n

要将本地时间转换为 UTC 时间,您可以尝试使用Date 对象 toUTCString()方法或Date.UTC()方法。

\n

编辑

\n

此外,ASP.NET Core MVC 支持使用输入和输出格式化程序在 Web API 中进行数据交换。输入格式化程序由模型绑定使用。输出格式化程序用于格式化响应

\n

您可以参考以下示例代码来格式化响应数据,它将把本地日期时间转换为UTC时间:

\n

创建自定义日期时间转换器:

\n
public class DateTimeConverter : JsonConverter<DateTime>\n{\n    public override DateTime Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)\n    {\n        Debug.Assert(typeToConvert == typeof(DateTime));\n        return DateTime.Parse(reader.GetString());\n    }\n\n    public override void Write(Utf8JsonWriter writer, DateTime value, JsonSerializerOptions options)\n    {\n        writer.WriteStringValue(value.ToUniversalTime().ToString("yyyy\'-\'MM\'-\'dd\'T\'HH\':\'mm\':\'ssZ"));\n    }\n}\n
Run Code Online (Sandbox Code Playgroud)\n

配置自定义转换器(在 ASP.NET Core 3.0 或更高版本中,默认 JSON 格式化程序基于 System.Text.Json):

\n
        services.AddControllersWithViews().AddJsonOptions(options =>\n        {\n            options.JsonSerializerOptions.Converters.Add(new DateTimeConverter());\n        });\n
Run Code Online (Sandbox Code Playgroud)\n

[注意]使用上面的代码,它只是格式化响应数据,而不是改变输入数据。

\n

对于输入格式化程序,您可以尝试创建自定义模型绑定来更改日期时间格式。

\n