10
7

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

JSON.stringifyでDateの時間が変わらないようにする

Last updated at Posted at 2019-07-12

Dateの時間が変わる

JavaScript
new Date();

結果は
Fri Jul 12 2019 10:00:00 GMT+0900 (日本標準時)

JavaScript
JSON.stringify({"now": new Date()});

結果は
"{"now":"2019-07-12T01:00:00.000Z"}"

10時から1時に変わって困った :disappointed_relieved:
JSON.stringifyでも日本時間にしたい。

なぜDateが変わるのか

JavaScript
new Date().toJSON();

結果は
"2019-07-12T01:00:00.000Z"

Date.prototype.toJSONが原因らしい。

Date.prototype.toJSONを上書きすればいいらしいが標準クラスを上書きしたくない。

JSON.stringifyのreplacerを使う

JavaScript
JSON.stringify({"now": new Date()}, function(key, value) {
   if (this[key] instanceof Date) {
      return this[key].toString();
   }
   return value;
});

結果は
"{"now":"Fri Jul 12 2019 10:00:00 GMT+0900 (日本標準時)"}"
となり、日本時間にできた :relaxed:

JSON.stringifyの構文は

JSON.stringify(value[, replacer[, space]])

Thanks

How to JSON stringify a javascript Date and preserve timezone - Stack Overflow

解法のアイデアはネタ元からだが日本語で書くことに意味があるのだ :sunglasses:

10
7
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
10
7

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?