问题描述
所以我从 Date().toLocaleString()
获取本地当前日期和时间。当我在浏览器中运行它或在本地点击这个 API 时,它给了我 IST 中的日期和时间(因为我来自印度)。但是当我将它部署到服务器时,我得到的时间更改为 UTC。正常吗?如果是这样,如何每次都获得 IST?
我的代码:
let currentDate = new Date().toLocaleString();
console.log(currentDate);
解决方法
toLocaleString() 方法返回一个字符串,该字符串具有该日期的语言敏感表示。新的语言环境和选项参数让应用程序指定应使用其格式约定的语言并自定义函数的行为。在忽略语言环境和选项参数的旧实现中,使用的语言环境和返回的字符串形式完全取决于实现。
示例:
var event = new Date(Date.UTC(2012,11,20,3,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() output format is different on the live server and localhost
,选项 1:
env TZ='Asia/Kolkata' node server.js
选项 2:
process.env.TZ = 'Asia/Kolkata'
选项 3(推荐): 使用这个 this module
const momentTZ = require('moment-timezone');
console.log(momentTZ().tz('Asia/Kolkata').toISOString());