12-31-2019 12:38
12-31-2019 12:38
I have a issue where I believe I am saving out the date as "Tue Dec 31 2019 14:33:12 GMT-06:00" but whenever it loads it comes back as "2019-12-31T20:32:25.000Z". I would appreciate any help in getting it back to "Tue Dec 31 2019 14:33:12 GMT-06:00". I have been reading through the code but everything I have attempted seems to also return that second string.
export function loadHistory() {
let historyObject;
try {
historyObject = JSON.parse(fs.readFileSync(FILE_HISTORY, FILE_TYPE));
} catch (ex) {
historyObject = {
date: new Date(),
}
saveHistory(historyObject);
}
return historyObject;
}
export function saveHistory(historyData) {
let historyJSON = JSON.stringify(historyData);
fs.writeFileSync(FILE_HISTORY, historyJSON, FILE_TYPE);
}
I'm probably missing something really obvious to some but this is my first time really working with Javascript.
Answered! Go to the Best Answer.
12-31-2019 12:47
12-31-2019 12:47
Saving and loading dates as strings is dangerous and not recommended: see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date
A safer approach is to save the date's value as an integer; eg, using getTime().
12-31-2019 12:47
12-31-2019 12:47
Saving and loading dates as strings is dangerous and not recommended: see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date
A safer approach is to save the date's value as an integer; eg, using getTime().
12-31-2019 13:02
12-31-2019 13:02
Alright I can make those changes. Any advice on getting the int back to the "Tues, December 31 2019" format? Working with the locales previously didn't really have much of an effect on the formatting.
12-31-2019 13:03
12-31-2019 13:03
Off the top of my head, have a look at Date constructors.