使用JsonConverter将日期UTC转换为特定时区

问题描述

很抱歉格式化。

我正在从数据库接收JSON响应,我需要将日期转换为他/她所在的每个用户的时区。我正在接收的用户时区为“ timezone”:5.5或“ timezone”:-6

仅供参考,我的应用程序正在Azure中运行。我还应该检查夏令时的时区。应用程序是用C#开发的。我已经尝试过thisthis 看起来Nodatime适用于根据时区转换日期。我是一个全新的人,尝试弄清楚如何根据时区更改JSON中的Date值。

我尝试下面的代码来查看日期是否正在更改,但是什么也没有发生。我不确定可以在哪里放置时区。任何帮助表示赞赏。

 ` var date = "2020-08-12T18:30:13.000";
    var json = $"{{\"Date\": \"{date}\"}}";

    var pattern = ZonedDateTimePattern.CreateWithInvariantCulture(
        "yyyy-MM-dd HH:mm:ss z",DateTimeZoneProviders.Tzdb
    );

    var settings = new JsonSerializerSettings
    {
        DateParseHandling = DateParseHandling.None,Converters = { new NodaPatternConverter<ZonedDateTime>(pattern) }
    };
    var dateObj = JsonConvert.DeserializeObject<DateObj>(json,settings);
    Console.WriteLine(dateObj.Date);`

下面是我正在接收的JSON

{
"entity": [
    {
        "JobId": 691230,"Operation Type": "Backup","Client": "cnwxwdevwms01","Agent": "Oracle Database","Instance": "T0340X","BackupSet": "default","Subclient": "ArchiveLog"," Backup Type": "Full","Start Time": "2020-08-12T18:30:16.000","End Time": "2020-08-12T18:32:04.000","Duration in Mins": 2,"Size of Application": 315621376,"Job Status": "Completed","dt": "2020-08-12T00:00:00.000","age": 0,"original_0": {
            "numberOfDays": "10","serverName": "cnwxwdevwms01"
        }
    },{
        "JobId": 691230,{
        "JobId": 694338,"Start Time": "2020-08-13T12:30:15.000","End Time": "2020-08-13T12:32:07.000","Size of Application": 282066944,"dt": "2020-08-13T00:00:00.000",{
        "JobId": 693664,"Start Time": "2020-08-13T06:30:24.000","End Time": "2020-08-13T06:32:13.000","Size of Application": 255852544,{
        "JobId": 692966,"Agent": "Windows File System","Instance": "N/A","BackupSet": "defaultBackupSet","Subclient": "default"," Backup Type": "Incremental","Start Time": "2020-08-13T02:00:19.000","End Time": "2020-08-13T04:00:14.000","Duration in Mins": 120,"Size of Application": 514155115394,{
        "JobId": 692656,"Start Time": "2020-08-13T00:30:17.000","End Time": "2020-08-13T00:32:13.000","Size of Application": 124780544,{
        "JobId": 691827,"Start Time": "2020-08-12T21:00:24.000","End Time": "2020-08-12T22:51:53.000","Duration in Mins": 111,"Size of Application": 683671552,"age": 1,"serverName": "cnwxwdevwms01"
        }
    }
]
}

解决方法

让我知道这是否对您有用。

我没有使用Nodatime,因为我认为不需要时区转换。 我看到的问题是您的datetime不包含任何时区信息。 .Net将其视为本地。 如Microsoft文档所述: The time zone component of DateTimeKind.Utc date and time values uses "Z" (which stands for zero offset) to represent UTC.

编辑(根据@Sanjeev Gautam的评论):当您的函数在Azure上运行时,您将需要找到一种方法来提取用户的本地时区。在下面的示例中,我使用了 UTC-9

指定使用UTC设置日期时间可以实现以下目的:

// Object Class
class DateObj
{
    public DateTime Date { get; set; }
}


// JsonConverter
class DateTimeConverterTimeZone : JsonConverter<DateTime>
{
    public TimeZoneInfo TimeZone { get; set; }

    public DateTimeConverterTimeZone(TimeZoneInfo timezone)
    {
        TimeZone = timezone;
    }

    public override void WriteJson(JsonWriter writer,DateTime value,JsonSerializer serializer)
    {
        writer.WriteValue(value.ToUniversalTime());
    }

    public override DateTime ReadJson(JsonReader reader,Type objectType,DateTime existingValue,bool hasExistingValue,JsonSerializer serializer)
    {
        DateTime  dt = (DateTime) reader.Value; 

        var newDateTime= TimeZoneInfo.ConvertTime(dt,TimeZone);
        return newDateTime;
    }
}

//Deserialization
var date = "2020-08-12T18:30:13.000Z";
var json = $"{{\"Date\": \"{date}\"}}";
var convertedDateTime = JsonConvert.DeserializeObject<DateObj>(json,new DateTimeConverterTimeZone(TimeZoneInfo.FindSystemTimeZoneById("UTC-09")));

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...