【问题标题】:Running Date().toLocaleString() gives me local time on local machine but UTC on server运行 Date().toLocaleString() 给我本地机器上的本地时间,但服务器上的 UTC
【发布时间】:2021-04-22 13:01:07
【问题描述】:

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

我的代码:

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

【问题讨论】:

    标签: javascript date time utc date-conversion


    【解决方案1】:

    toLocaleString() 方法返回一个字符串,该字符串具有该日期的语言敏感表示。新的语言环境和选项参数让应用程序指定应该使用其格式约定的语言并自定义函数的行为。在忽略语言环境和选项参数的旧实现中,使用的语言环境和返回的字符串形式完全取决于实现。

    例子:

    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() output format is different on the live server and localhost

    【讨论】:

      【解决方案2】:

      选项 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());
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-05-20
        • 1970-01-01
        • 2010-12-13
        • 2019-10-15
        • 1970-01-01
        • 2015-06-03
        相关资源
        最近更新 更多