Running Date(). tolocalestring()给我本地机器上的本地时间,但服务器上的UTC



所以我从Date().toLocaleString()获得本地当前日期和时间。当我在浏览器中运行它或在本地点击这个API时,它会给我IST中的日期和时间(因为我来自印度)。但是当我将它部署到服务器时,我得到的时间被更改为UTC。这正常吗?如果是,每次如何获得IST ?

我代码:

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

toLocaleString()方法返回一个具有该日期的语言敏感表示形式的字符串。新的locale和options参数允许应用程序指定应该使用其格式约定的语言,并自定义函数的行为。在旧的实现中,忽略locale和options参数,使用的区域设置和返回的字符串形式完全依赖于实现。

的例子:

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.

您没有将位置参数传递给toLocaleString,因此将使用当前位置。您在您的机器和远程服务器上看到的输出不同,因为它们物理上位于不同的国家/地区。

Date().toLocaleString()的输出格式在活动服务器和本地主机上是不同的

选项1:

env TZ='Asia/Kolkata' node server.js

选项2:

process.env.TZ = 'Asia/Kolkata' 

方案3(推荐):使用这个模块

const momentTZ = require('moment-timezone');
console.log(momentTZ().tz('Asia/Kolkata').toISOString());

最新更新