【问题标题】:Convert date UTC to a specific timezone using a JsonConverter使用 JsonConverter 将日期 UTC 转换为特定时区
【发布时间】:2020-08-15 11:49:41
【问题描述】:

我很抱歉我的格式化。

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

仅供参考,我的应用程序正在 Azure 中运行。我还应该检查时区的夏令时。应用程序是用 c# 开发的。我试过thisthis 看起来 Nodatime 适合根据时区转换日期。我对此完全陌生,并试图弄清楚如何根据时区更改 JSON 中的日期值。

我尝试了下面的代码来查看日期是否发生变化,但没有任何反应。我不确定我可以把时区放在哪里。任何帮助表示赞赏。

 ` 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,
        "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": 694338,
        "Operation Type": "Backup",
        "Client": "cnwxwdevwms01",
        "Agent": "Oracle Database",
        "Instance": "T0340X",
        "BackupSet": "default",
        "Subclient": "ArchiveLog",
        " Backup Type": "Full",
        "Start Time": "2020-08-13T12:30:15.000",
        "End Time": "2020-08-13T12:32:07.000",
        "Duration in Mins": 2,
        "Size of Application": 282066944,
        "Job Status": "Completed",
        "dt": "2020-08-13T00:00:00.000",
        "age": 0,
        "original_0": {
            "numberOfDays": "10",
            "serverName": "cnwxwdevwms01"
        }
    },
    {
        "JobId": 693664,
        "Operation Type": "Backup",
        "Client": "cnwxwdevwms01",
        "Agent": "Oracle Database",
        "Instance": "T0340X",
        "BackupSet": "default",
        "Subclient": "ArchiveLog",
        " Backup Type": "Full",
        "Start Time": "2020-08-13T06:30:24.000",
        "End Time": "2020-08-13T06:32:13.000",
        "Duration in Mins": 2,
        "Size of Application": 255852544,
        "Job Status": "Completed",
        "dt": "2020-08-13T00:00:00.000",
        "age": 0,
        "original_0": {
            "numberOfDays": "10",
            "serverName": "cnwxwdevwms01"
        }
    },
    {
        "JobId": 692966,
        "Operation Type": "Backup",
        "Client": "cnwxwdevwms01",
        "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,
        "Job Status": "Completed",
        "dt": "2020-08-13T00:00:00.000",
        "age": 0,
        "original_0": {
            "numberOfDays": "10",
            "serverName": "cnwxwdevwms01"
        }
    },
    {
        "JobId": 692656,
        "Operation Type": "Backup",
        "Client": "cnwxwdevwms01",
        "Agent": "Oracle Database",
        "Instance": "T0340X",
        "BackupSet": "default",
        "Subclient": "ArchiveLog",
        " Backup Type": "Full",
        "Start Time": "2020-08-13T00:30:17.000",
        "End Time": "2020-08-13T00:32:13.000",
        "Duration in Mins": 2,
        "Size of Application": 124780544,
        "Job Status": "Completed",
        "dt": "2020-08-13T00:00:00.000",
        "age": 0,
        "original_0": {
            "numberOfDays": "10",
            "serverName": "cnwxwdevwms01"
        }
    },
    {
        "JobId": 691827,
        "Operation Type": "Backup",
        "Client": "cnwxwdevwms01",
        "Agent": "Oracle Database",
        "Instance": "T0340X",
        "BackupSet": "default",
        "Subclient": "default",
        " Backup Type": "Incremental",
        "Start Time": "2020-08-12T21:00:24.000",
        "End Time": "2020-08-12T22:51:53.000",
        "Duration in Mins": 111,
        "Size of Application": 683671552,
        "Job Status": "Completed",
        "dt": "2020-08-13T00:00:00.000",
        "age": 1,
        "original_0": {
            "numberOfDays": "10",
            "serverName": "cnwxwdevwms01"
        }
    },
    {
        "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-13T00:00:00.000",
        "age": 1,
        "original_0": {
            "numberOfDays": "10",
            "serverName": "cnwxwdevwms01"
        }
    }
]
}

【问题讨论】:

  • 日期是否以 UTC 格式存储在您的数据库中?通常,如果它们的格式如下:'2020-08-12T18:30:13.000Z'。如果他们不是 UTC,你怎么知道他们将使用哪个时区?
  • 嗨,Jukien,是的,日期是 UTC。
  • 以后,请不要删除一个问题,然后稍微改变一下。相反,编辑现有问题。

标签: c# asp.net .net .net-core nodatime


【解决方案1】:

让我知道这是否适合你。

我没有使用 Nodatime,因为我认为它对于时区转换没有必要。 我看到的问题是您的日期时间不包含任何时区信息。 .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")));

【讨论】:

  • 嗨朱利安,感谢您的回复。我不能选择 DateTimeZoneHandling.Local,因为我的应用程序在 Azure 中运行,它总是需要 Azure 时区。我们需要给用户时区。
  • @SanjeevGautam - 感谢您的评论。我省略了“Azure”部分,抱歉。我更新了响应以使用自定义 JsonConverter。
  • 谢谢,它与日期共享。当我尝试使用我的实际 JSON 日期时没有转换。 var convertDateTimeFinal = JsonConvert.DeserializeObject(response.Content, new DateTimeConverterTimeZone(TimeZoneInfo.FindSystemTimeZoneById("UTC-09")));请提供任何帮助。
  • 您分享的日期最后没有指定它是 UTC 日期的 Z。您是否尝试在 Json 中每个日期的末尾添加 Z ?
  • 伟大的朱利安,你救了我:)。它就像一个魅力。
猜你喜欢
  • 2021-11-19
  • 2021-03-12
  • 1970-01-01
  • 2020-03-21
  • 1970-01-01
  • 1970-01-01
  • 2017-11-07
  • 2020-06-11
  • 2011-08-30
相关资源
最近更新 更多