1、编写显示时间的页面:
<html>
<head>
<meta http-equiv="Content-Type" content="text/htmlcharset=utf-8" />
<title>Server date/time</title>
<script language="javascript" src="serverDate.js"></script>
</head>
<script language="javascript">
var localTime = new Date()
document.write("Local machine time is: " + localTime + "<br>")
document.write("Server time is: " + date)
</script>
<body>
</body>
2、ajax脚本获取server的时间
var xmlHttp
function srvTime(){
try {
//创建xmlHttp对象
xmlHttp = new XMLHttpRequest()
}
catch (err1) {
//ie浏览器
try {
xmlHttp = new ActiveXObject('Msxml2.XMLHTTP')
}
catch (err2) {
try {
xmlHttp = new ActiveXObject('Microsoft.XMLHTTP')
}
catch (eerr3) {
//ajax不支持
alert("AJAX not supported")
}
}
}
//打开xmlHttp请求
xmlHttp.open('HEAD',window.location.href.toString(),false)
//设置xmlHttp请求头
xmlHttp.setRequestHeader("Content-Type", "text/html")
//发送请求
xmlHttp.send('')
// 获取response中的Date参数
return xmlHttp.getResponseHeader("Date")
}
var st = srvTime()//服务器时间赋值给st变量
var date = new Date(st)//转换js的date对象
// 输出服务器时间
document.write("服务器时间: " + date)
nodejs调了系统时间后date.now错误的原因是系统时间与实际时间不一致。让网站后台数据库存储当前的时间数据,需要经过前端脚本把本地电脑时间传递给后台,不能直接使用服务器的时间,这个时间是不能人为的控制的,导致date.now错误。给获取时间定义的一个获取时间方法,在该方法内去获取function getTime(){
var nowDate=new Date()
var year=nowDate.getFullYear()
var month=nowDate.getMonth()+1<10?"0"+(nowDate.getMonth()+1):nowDate.getMonth()+1
var date=nowDate.getDate()<10?"0"+nowDate.getDate():nowDate.getDate()
var hour=nowDate.getHours()<10?"0"+nowDate.getHours():nowDate.getHours()
var minute=nowDate.getMinutes()<10?"0"+nowDate.getMinutes():nowDate.getMinutes()
var second=nowDate.getSeconds()<10?"0"+nowDate.getSeconds():nowDate.getSeconds()
return year+month+date+hour+minute+second
}