簡體   English   中英

ASP.NET Core UTC 時間到本地

[英]ASP.NET Core UTC time to Local

我使用 ASP.NET Core 5 和 Entity Framework Core 作為我的 ORM。 從 Angular 應用程序獲取 UTC 時間。 但用戶將僅來自一個國家。 所以我決定將UTC時間轉換為本地時間——即印度的時區——同時保存到數據庫。

我的問題:

  1. 如何將 ASP.NET Core 應用程序配置為在存儲到數據庫時始終將 UTC 時間轉換為en-IN
  2. 另外,在將數據發送到 API 時,我需要將本地時間轉換回 UTC。

請任何人建議應用程序 Local time 始終是en-IN ,但托管在相同/不同的國家/地區。

請讓我知道如何將 UTC 時間轉換為本地時間(en-IN) ,反之亦然

在 asp.net core 中,將時間轉換為 UTC 的最簡單方法是調用靜態(在 Visual Basic 中共享)TimeZoneInfo.ConvertTimeToUtc(DateTime) 方法。

        DateTime dateNow = DateTime.Now;

        Console.WriteLine("Local date and time: " + dateNow);

        var kind = dateNow.Kind;
        Console.WriteLine("The date and time are {0} UTC.",
                           TimeZoneInfo.ConvertTimeToUtc(dateNow));

然后,要將 UTC 轉換為您指定的任何時區的時間,請調用 ConvertTimeFromUtc 方法。

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

更多詳細信息,請參閱在時區之間轉換時間DateTime.ToUniversalTime 方法(將日期時間字符串轉換為 DateTime 對象)。

此外,您還可以使用 JavaScript 在 UTC 時間和本地時間之間轉換日期時間。

要使用 JavaScript 將 UTC 時間轉換為本地日期時間(具有特定時區),您可以嘗試使用Date.prototype.toLocaleString()方法。

示例代碼如下:

const event = new Date(Date.UTC(2012, 11, 20, 3, 0, 0));

// British English uses day-month-year order and 24-hour time without AM/PM
console.log(event.toLocaleString('en-IN', { timeZone: 'UTC' }));
// expected output: 20/12/2012, 03:00:00

// Korean uses year-month-day order and 12-hour time with AM/PM
console.log(event.toLocaleString('ko-KR', { timeZone: 'UTC' }));
// expected output: 2012. 12. 20. 오전 3:00:00

console.log('USA time: '+ event.toLocaleString("en-US", {timeZone: "America/New_York"}))
// expected output: USA time: 2020-11-15T13:20:52.000Z 

console.log('India time: '+ event.toLocaleString("en-US", {timeZone: "Asia/Kolkata"}))
// expected output: India time: 2020-11-15T23:50:52.000Z

要將本地時間轉換為 UTC 時間,您可以嘗試使用日期對象 toUTCString()方法或Date.UTC()方法。

編輯

此外,ASP.NET Core MVC 支持使用輸入和輸出格式化程序在 Web API 中交換數據。 模型綁定使用輸入格式化程序。 輸出格式化程序用於格式化響應

您可以參考以下示例代碼來格式化響應數據,它將本地日期時間轉換為 UTC 時間:

創建自定義日期時間轉換器:

public class DateTimeConverter : JsonConverter<DateTime>
{
    public override DateTime Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
    {
        Debug.Assert(typeToConvert == typeof(DateTime));
        return DateTime.Parse(reader.GetString());
    }

    public override void Write(Utf8JsonWriter writer, DateTime value, JsonSerializerOptions options)
    {
        writer.WriteStringValue(value.ToUniversalTime().ToString("yyyy'-'MM'-'dd'T'HH':'mm':'ssZ"));
    }
}

配置自定義轉換器(在 ASP.NET Core 3.0 或更高版本中,默認 JSON 格式化程序基於 System.Text.Json):

        services.AddControllersWithViews().AddJsonOptions(options =>
        {
            options.JsonSerializerOptions.Converters.Add(new DateTimeConverter());
        });

[注意] 使用上面的代碼,它只是格式化響應數據,而不是改變輸入數據。

對於輸入格式化程序,您可以嘗試創建自定義模型綁定來更改日期時間格式。

Date.setMinutes()函數需要一個介於 0 和 59 之間的值。

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/setMinutes

我會獲取用戶的時區偏移量並將該值放入 cookie 中。 您如何編寫代碼取決於您的應用程序。 如果用戶必須登錄,那么我會在用戶登錄時獲取該值。 如果您使用的是 ASP 標識,那么您可以將時區偏移量存儲為聲明。 然后在日期函數更健壯的服務器上進行數學計算。

否則,您需要在 JavaScript 中編寫date.addMinutes函數或使用像 Moment 這樣的現有庫。

https://momentjs.com/

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM