Search code examples
javascriptdatelocalestring-formatting

Strange behavior of toLocaleString() method


I am little bit confused with strange behavior of toLocaleString method. Can someone to help to fix it please.

For example next code works correct:

let value = "2018-11-26T10:00:00.000Z";
let dateValue = new Date(value).toLocaleString('ru-RU');
console.log(dateValue); // return: 26.11.2018, 16:00:00

This code return strange result:

let value = "2018-11-26T10:00:00.000Z";
let dateValue = new Date(value);
let newDateValue = dateValue.setMonth(dateValue.getMonth() + 1).toLocaleString('ru-RU');
console.log(newDateValue); // return: 1 545 818 400 000

I expected that result would be 26.12.2018, 16:00:00


Solution

  • The return value of setMonth() is a number, not a Date. Just use the mutated dateValue instead:

    let value = "2018-11-26T10:00:00.000Z";
    let dateValue = new Date(value);
    
    dateValue.setMonth(dateValue.getMonth() + 1);
    
    let newDateValue = dateValue.toLocaleString('ru-RU');
    
    console.log(newDateValue); // return: 26.12.2018, 16:00:00