Created
June 7, 2020 14:52
-
-
Save nemoinho/a20fa661adf26755004a4a8d3e7e74a9 to your computer and use it in GitHub Desktop.
Wie funktioniert ein Datum in JSON
This file contains 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
/** | |
* Wir haben ein Datum, welches wir z.B. im localStorage speichern wollen und später wieder brauchen. | |
* Damit wir sehen was jeweils ausgegeben wird logge ich die Resultate via console.log und schreibe | |
* als Kommentar dazu, welche Ausgabe ich etwa erwarte | |
*/ | |
const someDate = new Date(); | |
console.log(someDate); // Ausgabe: Ein Datumsobjekt, zu sehen ist dessen String-Representation | |
const dateString = someDate.toString(); | |
console.log(dateString); // Ausgabe: Sun Jun 07 2020 16:37:35 GMT+0200 (Central European Summer Time) | |
const jsonSerializedDate = JSON.stringify(someDate); | |
console.log(jsonSerializedDate); // Ausgabe: "2020-06-07T14:36:32.672Z" | |
const deserializedJsonDate = JSON.parse(jsonSerializedDate); | |
console.log(deserializedJsonDate); // Ausgabe (quotes als Unterschied zu vorher): 2020-06-07T14:38:34.926Z | |
const parsedDeserializedDate = new Date(deserializedJsonDate); | |
console.log(parsedDeserializedDate); // Ausgabe: Die selbe Ausgabe wie bei someDate | |
// Weitere API zu Date, die bei der Arbeit mit Date hilft: | |
const timestamp = Date.now(); | |
console.log(timestamp); // Ausgabe: 1591540916759 | |
const timestampDate = new Date(timestamp); | |
console.log(timestampDate); // Ausgabe: Ein Datumsobjekt, wie bei someDate | |
const jsonSerializedTimestamp = JSON.stringify(timestamp); | |
console.log(jsonSerializedTimestamp); // Ausgabe: "1591540916759" | |
const deserializedJsonTimestamp = JSON.parse(jsonSerializedTimestamp); | |
console.log(deserializedJsonTimestamp); // Ausgabe: 1591540916759 | |
const parsedDeserializedJsonTimestamp = JSON.stringify(timestamp); | |
console.log(parsedDeserializedJsonTimestamp); // Ausgabe: Die selbe Ausgabe wie bei timestampDate | |
// Und noch ein kleiner übler Hack um Dates bei JSON.parse zurück zu bekommen ;-) | |
// Ohne weitere Erklärung, einfach nur als Beispiel. | |
function dateParse(key, value) { | |
const dateRegex = /^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d\.\d*(?:Z|[+-][\d|:]*)?$/; | |
return typeof value === 'string' && dateRegex.test(value) | |
? new Date(value) | |
: value; | |
} | |
const json = JSON.stringify(new Date()); | |
const deserializedAndParsedJsonDate = JSON.parse(json, dateParse); | |
console.log(deserializedAndParsedJsonDate); // Ausgabe: Ein Datumsobjekt, zu sehen ist dessen String-Representation |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment