英文:
Why DateTime is 1 day behind from .NET serialized JSON and momentjs format?
问题
以下是翻译好的部分:
"Here's the Date I've on Database for a generic record: 1952-05-17 00:00:00.000
. I do some query, and than I return the data serialized as JSON on client, this way:
return Json(new { data = dataFiltered, recordsFiltered = dataTotal, recordsTotal = dataTotal });
If I debug, the DataTime field is formatted as follow:
Expanding properties, that's the situation:
Looks correct. Now on client, I received the DateTime field as: /Date(-556250400000)/
If I try now to format it with momentjs moment(value).format("DD/MM/YYYY")
, I got 16/05/1952
, which is one day behind.
Why? And how can I fix it?"
英文:
Here's the Date I've on Database for a generic record: 1952-05-17 00:00:00.000
. I do some query, and than I return the data serialized as JSON on client, this way:
return Json(new { data = dataFiltered, recordsFiltered = dataTotal, recordsTotal = dataTotal });
If I debug, the DataTime field is formatted as follow:
Expanding properties, that's the situation:
Looks correct. Now on client, I received the DateTime field as: /Date(-556250400000)/
If I try now to format it with momentjs moment(value).format("DD/MM/YYYY")
, I got 16/05/1952
, which is one day behind.
Why? And how can I fix it?
答案1
得分: 1
/Date(-556250400000)/
代表着 1952-05-16T22:00:00Z。看起来,根据你的 JSON 转换配置,它假定该值为本地时间,并将其转换为 UTC。
理想情况下,我建议:
- 将你的数据库更改为使用日期类型而不是日期/时间类型。
- 如果你使用的是 .NET 6.0 或更高版本,请更改 .NET 代码以使用
DateOnly
。 - 更改 JSON 处理方式,将其序列化为 ISO-8601 日期("1952-05-17")。
从根本上看,在每一层中,看起来你都将其视为日期和时间(导致是否在 UTC 中的不明确性),而实际上你要表示的是一个日期。
如果你必须保留它在当前的表示方式,我建议在所有地方都使用 UTC,以避免考虑本地时区的因素。这意味着我会期望看到 DateOfBirth
属性显示一个 Kind
值为 Utc。
英文:
/Date(-556250400000)/
represents 1952-05-16T22:00:00Z. It looks like however you've configured the JSON conversion is assuming that the value is in local time, and converting it to UTC.
Ideally, I'd suggest:
- Changing your database to use a date type instead of a date/time type
- Changing the .NET code to use
DateOnly
if you're on .NET 6.0 or above - Changing the JSON handling to serialize it as an ISO-8601 date ("1952-05-17")
Fundamentally at every layer it looks like you're treating this as a date and time (leading to ambiguities as to whether it's in UTC or not) when what you're really trying to represent is a date.
If you must keep it in the current representation, I'd suggest using UTC everywhere, to avoid any local time zone considerations coming in. That means I'd expect to see the DateOfBirth
property showing a Kind
of Utc.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论