js获取服务器时间

来自:互联网
时间:2020-02-23
阅读:

公司官网使用的是dedecms,在自定义表单中新建了一个表单作为留言框,而且需要记录用户留言的时间。

初步是想法是用户打开页面的时候,记录时间,然后写入到一个隐藏的input里面,跟随表单提交即可。

原先使用获取时间的js如下:

$(function() {
    var nowDate = new Date();
    var str = nowDate.getFullYear() + "-" + (nowDate.getMonth() + 1) + "-" + nowDate.getDate() + " " + nowDate.getHours() + ":" + nowDate.getMinutes() + ":" + nowDate.getSeconds();
    document.getElementById("time").value = str;
});

html如下:

<input type="hidden" name="times" id="times" class="intxt" value="">

功能是实现了,但是后来查看留言时候发现,居然有些人留言是2008年,2009年,2010年等,我擦咧,这是穿越了吗?

才发现上面的js获取来的是用户电脑的时间,如果用户电脑时间不正确的话,就会出现上面说的那种情况。

百度一番,找到以下的可用JS:

ajax();
function ajax(option) {
    var xhr = null;
    if (window.XMLHttpRequest) {
        xhr = new window.XMLHttpRequest();
    } else { // ie
        xhr = new ActiveObject("Microsoft")
    }
    // 通过get的方式请求当前文件
    xhr.open("get", "/");
    xhr.send(null);
    // 监听请求状态变化
    xhr.onreadystatechange = function() {
        var time = null,
        curDate = null;
        if (xhr.readyState === 2) {
            // 获取响应头里的时间戳
            time = xhr.getResponseHeader("Date");
            console.log(xhr.getAllResponseHeaders()) curDate = new Date(time);
            document.getElementById("time").innerHTML = "服务器时间是:" + curDate.getFullYear() + "-" + (curDate.getMonth() + 1) + "-" + curDate.getDate() + " " + curDate.getHours() + ":" + curDate.getMinutes() + ":" + curDate.getSeconds();
        }
    }
}

html如下:

<p id="time"></p>

这样子获取到的时间就是服务器上面的时间啦,只要服务器时间正常就好了。

返回顶部
顶部