2

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.

8
  • which one is correct? Commented Oct 1, 2019 at 12:00
  • 1
    In this cases I would adopt a library like moment.js in both node and browser. Commented Oct 1, 2019 at 12:02
  • 1
    I would guess that the first one is correct. The "en-NL" locale is a little unusual; Node can be augmented with ICU data at runtime. Commented Oct 1, 2019 at 12:02
  • 1
    It's also worth pointing out -> the locale used and the form of the string returned are entirely implementation dependent. Commented Oct 1, 2019 at 12:05
  • But i need exactly same output in node js like browser Commented Oct 1, 2019 at 12:07

2 Answers 2

2

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');
Sign up to request clarification or add additional context in comments.

Comments

2

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));

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.