【问题标题】:Working out timezone offsets when transferring data from PHP to JavaScript将数据从 PHP 传输到 JavaScript 时计算时区偏移量
【发布时间】:2012-08-11 03:05:59
【问题描述】:

好的,这是一个奇怪的问题。在我的一项修改中,PHP 代码使用 time() 将时间戳存储在数据库中——据我所知,这使用 UTC 时区。现在,我获取这些数据并将其用作某个 Javascript 函数中的参数。该函数返回一个时间字符串,类似于“30 秒前”或“2 小时 30 分钟前”等。这是完整的函数:

time_string : function(seconds,complexity,seconds_left,suffix,prefix){
    var difference = Math.abs(dynamo.time - seconds);
    seconds_left = seconds_left == null ? 0 : seconds_left;
    seconds = +seconds;
    if(difference < 15 && !seconds_left){
        return "Just now";
    }
    suffix = suffix != null
        ? (seconds_left == 1
            ? ""
            : suffix)
        : (seconds_left == 1
            ? ""
            : " ago");
    prefix = prefix != null ? prefix : "";
    if(difference > 86400){
        return new Date(seconds * 1000).toDateString();
    } else {
        var years = Math.floor(difference / 31536000);
        var days = Math.floor((difference / 86400) % 365);
        var hours = Math.floor((difference / 3600) % 24);
        var minutes = Math.floor((difference / 60) % 60);
        var second = difference % 60;
        var time_str = [];
        if(years > 0) time_str[time_str.length] = dynamo.toolbox.format_number(years) + " year" + (years == 1 ? '' : 's');
        if(days > 0) time_str[time_str.length] = days + " day" + (days == 1 ? '' : 's');
        if(hours > 0) time_str[time_str.length] = hours + " hour" + (hours == 1 ? '' : 's');
        if(days <= 1){
            if(minutes > 0) time_str[time_str.length] = minutes + " minute" + (minutes == 1 ? '' : 's');
            if(second > 0 && !minutes && !hours && !days){
                time_str[time_str.length] = second + " second" + (second == 1 ? '' : 's');
            }
        }
        complexity = complexity != null ? complexity : 2;
        time_str = time_str.slice(0,complexity);
        if(time_str.length > 1){
            var final_str = time_str[time_str.length-1];
            time_str.pop();
            time_str = time_str.join(", ") + " and " + final_str;
        } else {
            time_str = time_str.join("");
        }
    }
    return prefix + time_str + suffix;
}

在代码中,使用了dynamo.timedynamo.time 设置为来自 PHP 的当前 time()(我用它来计算存储时间和当前时间之间的时间差)。

但是,我需要调整 difference 变量以说明客户端与服务器的时区差异(和以前一样,我认为是 UTC)。

我该怎么做呢?

如果你想要的话,这里有一个 JS Fiddle,对函数进行了一些测试:http://jsfiddle.net/Jskjv/1/

编辑:我可以用 new Date().getTimezoneOffset() 来实现这个吗?唯一的问题是会与 DST 不一致。

【问题讨论】:

    标签: php javascript timezone


    【解决方案1】:

    我不确定混乱来自哪里;假设访客系统时钟足够好,您可以将任何时间戳与此进行比较:

    Math.round(new Date().getTime() / 1000)
    

    它还返回相同类型的 unix 时间戳,因此没有时区偏移的复杂性。

    可能是用户系统时钟太乱了。在这些情况下,您可以进行时间偏移计算,从而通过内联 JavaScript 传递 PHP 的 time()。同样,没有时区:)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-09-06
      • 2011-06-11
      • 2010-10-22
      • 2020-08-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多