迹忆客 专注技术分享

当前位置:主页 > 学无止境 > WEB前端 > JavaScript >

如何在 JavaScript 中解析 JSON 日期

作者:迹忆客 最近更新:2022/10/10 浏览次数:

要解析 JSON 日期:

  1. 使用 toJSON() 方法获取 Date 对象的字符串表示形式。
  2. 将 JSON 字符串传递给 Date() 构造函数。
  3. Date() 构造函数将解析 ISO 字符串并创建一个 Date 对象。
const json = new Date().toJSON();

console.log(json); // 👉️ "2022-10-06T14:29:28.109Z"

const date = new Date(json);

console.log(date); // 👉️ Thur Oct 26 2022 14:29:28

可以对有效的 Date 对象调用 toJSON() 方法。

该方法以 ISO 8601 格式返回给定日期的字符串表示形式。

我们可以将调用方法的结果传递给 Date() 构造函数,以从 JSON 字符串创建 Date 对象。

这是相同的示例,但使用了更手动的方法。

const json = JSON.stringify(new Date().toISOString());

console.log(json); // 👉️ "2022-10-06T14:29:28.109Z"

const date = new Date(JSON.parse(json));

console.log(date); // 👉️ Thur Oct 26 2022 14:29:28

// 👇️ "2022-10-06T14:29:28.109Z"
console.log(date.toISOString());

我们使用 toISOString() 方法获取一个字符串,该字符串表示 ISO 8601 格式的给定日期 - YYYY-MM-DDTHH:mm:ss.sssZ

使用 toISOString 方法时,我们始终会根据通用时间获取日期。

toJSON() 方法在底层使用 toISOString() 方法,因此两个代码片段是等价的,第二个更明确。

toISOString 方法根据通用时间返回结果,因此字符串显示的时间为 09:04:45,而 Date 对象的时间设置为 11:04:45

这是因为我的时区比协调世界时 (UTC) 早 2 小时。

大多数情况下,在存储日期时,建议在数据库中存储时间戳或有效的 ISO 8601 字符串 (UTC)。

例如,如果我们将当地时间午夜 (00:00) 存储在数据库中,您将不知道这是东京(日本)、巴黎(法国)、纽约(美国)等的午夜。这些都是相隔数小时的不同时刻。

为了保持一致性,当我们必须向用户呈现日期和时间时,您应该主要使用本地时间,但将实际值存储在 UTC (=GMT) 中。

在 JavaScript 中获取日期的 ISO 格式字符串非常容易。我们只需使用 toISOString()方法。

console.log(new Date().toISOString());

使用 JSON.stringify 方法可以轻松地将字符串转换为 JSON,然后可以通过网络传输。

Date() 构造函数知道如何解析 ISO 8601 字符串,因此我们所要做的就是解析 JSON 并将 ISO 字符串传递给构造函数。

const json = JSON.stringify(new Date().toISOString());

console.log(json); // 👉️ "2022-10-06T14:36:08.488Z"

const date = new Date(JSON.parse(json));

console.log(date); // 👉️ Thur Oct 26 2022 14:36:08

转载请发邮件至 1244347461@qq.com 进行申请,经作者同意之后,转载请以链接形式注明出处

本文地址:

相关文章

Do you understand JavaScript closures?

发布时间:2025/02/21 浏览次数:108 分类:JavaScript

The function of a closure can be inferred from its name, suggesting that it is related to the concept of scope. A closure itself is a core concept in JavaScript, and being a core concept, it is naturally also a difficult one.

Do you know about the hidden traps in variables in JavaScript?

发布时间:2025/02/21 浏览次数:178 分类:JavaScript

Whether you're just starting to learn JavaScript or have been using it for a long time, I believe you'll encounter some traps related to JavaScript variable scope. The goal is to identify these traps before you fall into them, in order to av

How much do you know about the Prototype Chain?

发布时间:2025/02/21 浏览次数:150 分类:JavaScript

The prototype chain can be considered one of the core features of JavaScript, and certainly one of its more challenging aspects. If you've learned other object-oriented programming languages, you may find it somewhat confusing when you start

JavaScript POST

发布时间:2024/03/23 浏览次数:96 分类:JavaScript

本教程讲解如何在不使用 JavaScript 表单的情况下发送 POST 数据。

扫一扫阅读全部技术教程

社交账号
  • https://www.github.com/onmpw
  • qq:1244347461

最新推荐

教程更新

热门标签

扫码一下
查看教程更方便