You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Date.prototype.toJSON は this 値を Number 型に変換した値が有限数であった場合、Date.prototype.toISOString を呼び出し、その返り値をそのまま返します。
つまり、Date.prototype.toISOString と同じ実行結果を返します。
(※このメソッドは JSON.stringify() で Date オブジェクトをシリアライズ(文字列化)する為に定義されており、通常は明示的に呼び出す事はありません。)
vardate=newDate("2017-08-23T12:00:00.000+09:00");console.log(date);// Wed Aug 23 2017 12:00:00 GMT+0900 (東京 (標準時))console.log(date.toJSON());// 2017-08-23T03:00:00.000Z
JSON.stringify( value [ , replacer [ , space ] ] )
期待通り、Date オブジェクトに戻す事が出来ました。
しかし、このままでは元々、文字列として存在した "2017-08-22T00:00:00.000Z" も Date オブジェクトに変換されてしまうので、JSON.stringify() にもコールバック関数を与えてみましょう。
'use strict';functionreviver(key,value){if(/date:\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z/.test(value)){// new Date ならreturnnewDate(value);}if(/string:\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z/.test(value)){// String 型ならreturnvalue.slice(7);}returnvalue;}functionreplacer(key,value){if(Object(value)===value&&Object.getPrototypeOf(value)===Date.prototype){// new Date ならreturn'date:'+date.toISOString();}if(typeofvalue==='string'){// String 型ならreturn'string:'+value;}returnvalue;}vardate=newDate('2017-08-22T09:00:00+09:00'),array1=[date,date.toISOString()],json=JSON.stringify(array1,replacer),array2=JSON.parse(json,reviver);console.log(array1);// [Tue Aug 22 2017 09:00:00 GMT+0900 (東京 (標準時)), "2017-08-22T00:00:00.000Z"]console.log(array2);// ["2017-08-22T00:00:00.000Z", "2017-08-22T00:00:00.000Z"]console.log(json);// ["string:2017-08-22T00:00:00.000Z","string:2017-08-22T00:00:00.000Z"]
期待に反して、両方とも「文字列」として扱われてしまいました。
なぜなら、replacer() を通した時点で Date オブジェクトは既に「ISO 8061拡張形式」の文字列に変換されてしまっているからです。