Search code examples
javascriptdatetimeutcdate-conversion

Running Date().toLocaleString() gives me local time on local machine but UTC on server


So I'm getting the local current date and time from Date().toLocaleString(). When I run it in the browser or hit this API locally, it gives me the date and time in IST (Since I'm from India). But when I deploy it to the server, the time I get is changed to UTC. Is it normal? If so, how to get the IST everytime?

My code:

 let currentDate = new Date().toLocaleString();
 console.log(currentDate);

Solution

  • The toLocaleString() method returns a string with a language sensitive representation of this date. The new locales and options arguments let applications specify the language whose formatting conventions should be used and customize the behavior of the function. In older implementations, which ignore the locales and options arguments, the locale used and the form of the string returned are entirely implementation dependent.

    Example:

    var event = new Date(Date.UTC(2012, 11, 20, 3, 0, 0));
    
    // British English uses day-month-year order and 24-hour time without AM/PM
    console.log(event.toLocaleString('en-GB', { timeZone: 'UTC' }));
    // expected output: 20/12/2012, 03:00:00
    
    // Korean uses year-month-day order and 12-hour time with AM/PM
    console.log(event.toLocaleString('ko-KR', { timeZone: 'UTC' }));
    // expected output: 2012. 12. 20. 오전 3:00:00
    You are not passing the location parameter to toLocaleString, so the current location will be used. You see a different output on your machine vs. remote server because they are physically located in different countries.
    
    

    You are not passing the location parameter to toLocaleString, so the current location will be used. You see a different output on your machine vs. remote server because they are physically located in different countries.

    Date().toLocaleString() output format is different on the live server and localhost