📅  最后修改于: 2023-12-03 15:02:25.930000             🧑  作者: Mango
JSON (JavaScript Object Notation) is a lightweight data-interchange format that is easy to read and write. It is widely used for exchanging data between different platforms and programming languages. In JavaScript, JSON is a built-in object that provides methods to convert JavaScript objects into a JSON string and vice versa.
When dealing with dates and times in JSON, there are a few considerations to keep in mind. JavaScript's built-in Date object uses a timestamp format that represents the number of milliseconds since January 1, 1970. However, JSON does not have a native way to represent dates or times.
To represent dates in JSON, there are two common formats:
To convert between JavaScript Date objects and JSON formats, there are a few methods to use:
JSON.stringify()
can be used to convert a JavaScript object to a JSON string. Dates will be converted to ISO 8601 format by default.let date = new Date();
let jsonString = JSON.stringify({ "timestamp": date });
console.log(jsonString); // {"timestamp":"2022-09-30T16:30:00.000Z"}
JSON.parse()
can be used to parse a JSON string and convert it to a JavaScript object. Dates in ISO 8601 format will be automatically converted to JavaScript Date objects, so that you can use Date methods to manipulate them.let jsonString = '{"timestamp":"2022-09-30T16:30:00.000Z"}';
let jsonParsed = JSON.parse(jsonString);
let date = new Date(jsonParsed.timestamp);
console.log(date.getFullYear()); // 2022
new Date(unixTimestamp * 1000)
.let unixTimestamp = 1661997600;
let date = new Date(unixTimestamp * 1000);
console.log(date); // Fri Sep 30 2022 16:30:00 GMT+0800 (中国标准时间)
This is a brief introduction to dealing with JSON Datetime in JavaScript. For more advanced usage, refer to the official documentation.
JSON is a lightweight and popular data interchange format used in JavaScript. When working with dates in JSON, it is important to use a standard format such as ISO 8601 or Unix timestamp. By making use of JSON.parse()
and JSON.stringify()
, you can easily convert between JavaScript Date objects and JSON formats.