Aunog
Aunog

Reputation: 47

JavaScript date conversion resulting in different values for Browser and Node js

I am using a function to convert date time into 'en-NL' format.But it gives me different result in browser and nodejs

function convertDateTime(value){
    const timestamp = new Date(value);
    let date = timestamp.toLocaleDateString('en-NL');
    let time = timestamp.toLocaleTimeString('en-NL');
    return date + ' ' + time;
}
console.log(convertDateTime(1559742499937));

when i use this function in browser it gives me following results: 05/06/2019 19:48:19 when i use this function in nodejs it gives me following result : 6/5/2019 7:48:19 PM. But my result should be same in browser and nodejs.

Upvotes: 2

Views: 1061

Answers (2)

Jaromanda X
Jaromanda X

Reputation: 1

If you don't want to include momentjs just for this simple function, you can always write your code to return the exact format you need

function convertDateTime(value){
    const t = new Date(value);
    const pad2 = n => ('0' + n).substr(-2);
    let date = `${pad2(t.getDate())}/${pad2(t.getMonth()+1)}/${t.getFullYear()}`
    let time = `${pad2(t.getHours())}:${pad2(t.getMinutes())}:${pad2(t.getSeconds())}`
    return date + ' ' + time;
}
console.log(convertDateTime(1559742499937));

Upvotes: 2

oktapodia
oktapodia

Reputation: 1748

The implementation of Date between browsers and node can differ a bit.

To avoid that issue, I suggest you to use a library like momentjs on both frontend and backend, afterward, you will be able to manage the format of the date and you should have the same value on both.

You can also force the format of the datetime with the following

moment().format('DD/MM/YY h:mm:ss');

Upvotes: 2

Related Questions