客户端和服务器端时间一致性解决方案

有两种情况:

1、WEB端使用ajax等方式访问

直接获取服务器端所返回header头中的date参数,以下采用js模拟该过程

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>WEB端和服务器端时间一致性解决方案</title>
</head>
<body>
<div id="remote_date"></div>
</body>
</html>
<script>
    var request = new XMLHttpRequest();
    request.open("GET", "remote.txt", true);
    request.send();

    var headerMap = [];
    request.onreadystatechange = function () {
        if (this.readyState == this.HEADERS_RECEIVED) {

            // Get the raw header string
            var headers = request.getAllResponseHeaders();

            // Convert the header string into an array
            // of individual headers
            var arr = headers.trim().split(/[\r\n]+/);

            // Create a map of header names to values

            arr.forEach(function (line) {
                var parts = line.split(': ');
                var header = parts.shift();
                headerMap[header] = parts.join(': ');
            });
            // 输出到页面
            document.getElementById('remote_date').innerText = getRemoteDate(headerMap['date']);
        }

    };


    function getRemoteDate(rawDate) {
        var time, year, month, date, hours, minutes, seconds;

        time = new Date(rawDate);
        year = time.getFullYear();

        // 小于10的数在前面加上0
        month = (time.getMonth() + 1) < 10 ? ("0" + (time.getMonth() + 1)) : (time.getMonth() + 1)
        date = time.getDate() < 10 ? ("0" + time.getDate()) : time.getDate();
        hours = time.getHours() < 10 ? ("0" + time.getHours()) : time.getHours();
        minutes = (time.getMinutes() < 10 ? ("0" + time.getMinutes()) : time.getMinutes());
        seconds = (time.getSeconds() < 10 ? ("0" + time.getSeconds()) : time.getSeconds());
        time = year + "-" + month + "-" + date + " " + hours + ":" + minutes + ":" + seconds;

        return time;
    }
</script>

2、APP端调用接口访问

服务器端单独提供一个获取时间接口让APP端调用

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值