【问题标题】:How to change the date in javascript having different timezones如何更改具有不同时区的javascript中的日期
【发布时间】:2014-06-16 12:26:59
【问题描述】:

我将日期保存在 unix-timestamp 中的数据库中。我已将时区默认设置为:

date_default_timezone_set("America/Los_Angeles");

但在 javascript 中,我通过以下方式更改时间戳:

for (var i = 0; i < records.length; i++) {
    if (originalData[i].SystemLogsUserAction.TimeStamp == "0") {
        records[i].TimeStamp = "";
    } else {
        records[i].TimeStamp = new Date(originalData[i].SystemLogsUserAction.TimeStamp * 1000);
    }
}
return records;

上面的代码改变了时间,但不是我提到的时区。

【问题讨论】:

  • 如果您正在处理时区,您可能需要考虑存储 UTC 时间和时区偏移量。
  • 我完全同意 Ron 的观点,尝试以 UTC 时间存储时间,这样在它们之间转换时更容易。您可以确定存储在数据库中的所有时间都具有相同的时区。
  • 我已将时区存储在我的 core.php 文件中,例如:- date_default_timezone_set("America/Los_Angeles");
  • 如果您不想遇到问题,请从头开始干净地设计您的应用程序。让您的服务器时区为 UTC。将您的数据库配置为 UTC。仅存储 UTC 时间戳 (zoned timestamp - timedelta = UTC timestamp)。显示时从 UTC 转换为用户 TZ (UTC timestamp + timedelta = zoned timestamp)。如果你从一开始就干净利落,那么你就不会那么容易遇到问题了。
  • 我不明白你想让我怎么做..

标签: javascript php date datetime timestamp-with-timezone


【解决方案1】:

无耻盗取自:http://www.techrepublic.com/article/convert-the-local-time-to-another-time-zone-with-this-javascript/6016329

// function to calculate local time
// in a different city
// given the city's UTC offset
function calcTime(city, offset) {

    // create Date object for current location
    d = new Date();

    // convert to msec
    // add local time zone offset
    // get UTC time in msec
    utc = d.getTime() + (d.getTimezoneOffset() * 60000);

    // create new Date object for different city
    // using supplied offset
    nd = new Date(utc + (3600000*offset));

    // return time as a string
    return "The local time in " + city + " is " + nd.toLocaleString();

}

此函数可用于通过提供城市/国家名称和偏移值来计算时区值

【讨论】:

    猜你喜欢
    • 2020-10-09
    • 2022-06-14
    • 2018-01-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-03
    • 1970-01-01
    相关资源
    最近更新 更多