对于内部计算机时钟关闭的用户,您如何在 JavaScript 中标准化客户端时间戳?请注意,我正在处理 UTC 时间。
我有一个 AWS ElasticSearch 实例,在此过程中设置了多个批处理和节流操作,这使得服务器端时间戳不可靠(因为数据可能无序,而顺序很重要)。因此,我需要使我的客户端时间戳更可靠。
我无法发出任何服务器端请求(需要将 HTTP 请求保持在最低限度),但是我可以包含在我的 javascript 首次加载到客户端时生成的服务器端时间戳。
外部定义的变量:
serverTimestamp - UTC 时间戳(以毫秒为单位),在加载 javascript 时在服务器端生成。getCookie - 获取给定键的 cookie 值的函数(如果未找到,则为空字符串)。文件的缓存控制设置是"public,max-age=300,must-revalidate"(所以 5 分钟)。
const getTimestamp = (function() {
    // This cookie is set on the `unload` event, and so should be greater than
    // the server-side timestamp when set.
    /** @type {!number} */
    const cookieTimestamp = parseInt(getCookie("timestamp_cookie"), 10) || 0;
    // This timestamp _should_ be a maximum of 5 minutes behind on page load
    // (cache lasts 5 min for this file).
    /** @type {!number} */
    const storedTimestamp = cookieTimestamp > serverTimestamp ?
                            cookieTimestamp : serverTimestamp;
    return function () {
        /** @type {!number} */
        const timestamp = Date.now();
        // This timestamp should be, at a *maximum*, 5-6 minutes behind
        // (assuming the user doesn't have caching issues)
        /** @type {!number} */
        const backupTimestamp = storedTimestamp
            + parseFloat(window.performance.now().toFixed(0));
        // Now let's check to see if the user's clock is
        // either too fast, or too slow:
        if (
            // Timestamp is smaller than the stored one.
            // This means the user's clock is too slow.
            timestamp < backupTimestamp
            // Timestamp is more than 6 minutes ahead. User's clock is too fast.
            // (Using 6 minutes instead of 5 to have 1 minute of padding)
            || (timestamp - backupTimestamp) > 360000
        ) {
            return backupTimestamp;
        } else {
            // Seems like the user's clock isn't too fast or too slow
            // (or just maximum 1 minute fast)
            return timestamp;
        }
    }
})();
使用上述getTimestamp功能,(new Date(getTimestamp())).getUTCDate()对于某些用户来说,运行是在第二天返回,并且getUTCHours在边缘情况下似乎到处都是。我无法自行诊断问题。
坚持客户端的时间戳 - 不要为日期/时间而烦恼。在客户端上存储服务器端和客户端时钟之间的增量。将客户端时间戳和增量与消息一起发送,然后在服务器上重建日期/时间。
然后,您可以在服务器端就如何处理时钟同步中的抖动和跳跃做出明智的决定。
| 归档时间: | 
 | 
| 查看次数: | 215 次 | 
| 最近记录: |