js 获取服务器时间出错获取1970问题

其实出现1970-01这个问题最终是浏览器的兼容问题,由于IE浏览器的缓存机制,导致请求头没有请求到,所以返回计算机的默认时间1970-01
有bug的代码:
var stuVdate = new Date( . a j a x ( a s y n c : f a l s e ) . g e t R e s p o n s e H e a d e r ( " D a t e " ) ) ; / / 取 得 当 前 时 间 f u n c t i o n d a t e T i m e F o r m a t ( d a t e ) v a r d = n e w D a t e ( d a t e ) ; v a r y e a r = d . g e t F u l l Y e a r ( ) ; v a r m o n t h = ( ′ 0 ′ + ( d . g e t M o n t h ( ) + 1 ) ) . s l i c e ( − 2 ) ; v a r d a y = ( ′ 0 ′ + ( d . g e t D a t e ( ) ) ) . s l i c e ( − 2 ) ; v a r h o u r = ( ′ 0 ′ + ( d . g e t H o u r s ( ) ) ) . s l i c e ( − 2 ) ; v a r m i n u t e s = ( ′ 0 ′ + ( d . g e t M i n u t e s ( ) ) ) . s l i c e ( − 2 ) ; v a r s e c o n d s = ( ′ 0 ′ + ( d . g e t S e c o n d s ( ) ) ) . s l i c e ( − 2 ) ; r e t u r n y e a r + " − " + m o n t h + " − " + d a y + " " + h o u r + " : " + m i n u t e s + " : " + s e c o n d s ; 解 决 后 代 码 : v a r s t u V d a t e = d a t e T i m e F o r m a t ( .ajax({async:false}).getResponseHeader("Date")); //取得当前时间 function dateTimeFormat(date){ var d = new Date(date); var year = d.getFullYear(); var month = ('0' + (d.getMonth() + 1)).slice(-2); var day = ('0' + (d.getDate())).slice(-2); var hour = ('0' + (d.getHours())).slice(-2); var minutes = ('0' + (d.getMinutes())).slice(-2); var seconds = ('0' + (d.getSeconds())).slice(-2); return year + "-" + month + "-" + day + " " + hour + ":" + minutes + ":" + seconds; } 解决后代码: var stuVdate = dateTimeFormat( .ajax(async:false).getResponseHeader("Date"));//functiondateTimeFormat(date)vard=newDate(date);varyear=d.getFullYear();varmonth=(0+(d.getMonth()+1)).slice(2);varday=(0+(d.getDate())).slice(2);varhour=(0+(d.getHours())).slice(2);varminutes=(0+(d.getMinutes())).slice(2);varseconds=(0+(d.getSeconds())).slice(2);returnyear+""+month+""+day+""+hour+":"+minutes+":"+seconds;varstuVdate=dateTimeFormat(.ajax({async:false}).getResponseHeader(“Date”));
//取得当前时间
function dateTimeFormat(date){
var d = new Date(date);
var year = d.getFullYear();
var month = (‘0’ + (d.getMonth() + 1)).slice(-2);
var day = (‘0’ + (d.getDate())).slice(-2);
var hour = (‘0’ + (d.getHours())).slice(-2);
var minutes = (‘0’ + (d.getMinutes())).slice(-2);
var seconds = (‘0’ + (d.getSeconds())).slice(-2);
return year + “-” + month + “-” + day + " " + hour + “:” + minutes + “:” + seconds;
}
相当于关闭浏览器的缓存,而加入type:"HEAD"是为了请求更快,默认为请求头

猜你喜欢

转载自blog.csdn.net/qq_36912167/article/details/105361242