Cancel
Showing results for 
Show  only  | Search instead for 
Did you mean: 

Trouble working with Date when loading from a JSON file.

ANSWERED

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. 

Best Answer
0 Votes
1 BEST ANSWER

Accepted Solutions

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().

Peter McLennan
Gondwana Software

View best answer in original post

Best Answer
0 Votes
3 REPLIES 3

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().

Peter McLennan
Gondwana Software
Best Answer
0 Votes

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.

Best Answer
0 Votes

Off the top of my head, have a look at Date constructors.

Peter McLennan
Gondwana Software
Best Answer