我們都知道直接使用 new Date() 獲取到的是訪問(wèn)當(dāng)前網(wǎng)站的客戶機(jī)本地的時(shí)間踢械,有的時(shí)候這個(gè)時(shí)間有可能因?yàn)槿藶樾薷募榍纾靼咫姵貨](méi)電等原因?qū)е芦@取到的時(shí)間不準(zhǔn)確。因此监署,在開(kāi)發(fā)中颤专,需要獲取當(dāng)前時(shí)間進(jìn)行操作,應(yīng)該直接使用JS獲取服務(wù)器的時(shí)間钠乏。
獲取本地當(dāng)前時(shí)間(時(shí)間戳):
var nowTime = new Date().getTime()/1000;
獲取服務(wù)器當(dāng)前時(shí)間(時(shí)間戳):
// 創(chuàng)建全局變量栖秕,也可以是局部的
var serverTime = ''
// 通過(guò)ajax訪問(wèn)服務(wù)器,獲取服務(wù)器時(shí)間
$.ajax({
async: false,
type: "GET",
success: function(result, status, xhr) {
serverTime = new Date( xhr.getResponseHeader("Date"));
serverTime = (new Date(serverTime)).getTime() / 1000;
},
error: function (a) {
}
});
時(shí)間戳轉(zhuǎn)換為日期格式:
var time, year, month, date, hours, minutes, seconds;
time = new Date();
year = time.getFullYear();
//以下是通過(guò)三元運(yùn)算對(duì)日期進(jìn)行處理,小于10的數(shù)在前面加上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());
//拼成自己想要的日期格式晓避,2018-01-15 19:05:33
time = year + "-" + month + "-" + date + " " + hours + ":" + minutes + ":" + seconds;
console.log(time)
封裝成方法:
function filterTime(time) {
var date = new Date(time)
var Y = date.getFullYear()
var M = date.getMonth() + 1 < 10 ? '0'+(date.getMonth()+1) : date.getMonth()+1
var D = date.getDate()
var hours = date.getHours() < 10 ? ("0" + date.getHours()) : date.getHours();
var minutes = (date.getMinutes() < 10 ? ("0" + date.getMinutes()) : date.getMinutes());
var seconds = (date.getSeconds() < 10 ? ("0" + date.getSeconds()) : date.getSeconds());
return `${Y}-${M}-${D} ${hours}:${minutes}:${seconds}`
}