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)
function showTime() {var now = new Date()
var nowTime = now.toLocaleString()
var date = nowTime.substring(0,10)//截取日期
var time = nowTime.substring(10,20) //截取时间
var week = now.getDay() //星期
var hour = now.getHours() //小时
//判断星期几
var weeks = ["日","一","二","三","四","五","六"]
var getWeek = "星期" + weeks[week]
var sc
//判断是AM or PM
if(hour >= 0 && hour < 5){
sc = '凌晨'
}
else if(hour > 5 && hour <= 7){
sc = '早上'
}
else if(hour > 7 && hour <= 11){
sc = '上午'
}
else if(hour > 11 && hour <= 13){
sc = '中午'
}
else if(hour> 13 && hour <= 18){
sc = '下午'
}
else if(hour > 18 && hour <= 23){
sc = '晚上'
}
document.getElementById('time').innerHTML ="当前时间:" + date+" " + getWeek +"&nbsp"+" "+sc+" "+time
setTimeout('showTime()',1000)
}
</script>
调用方法:
<body onload="showTime()">
<div id="time"></div>
</body>
2.简洁的办法: 显示格式: 当前时间: 2010年6月1日 10:00:00 星期一
<htmtl>
<head></head>
<body>
<div id="linkweb" style=" display:inline"></div>
<script>
setInterval("document.getElementById('linkweb').innerHTML=new Date ().toLocaleString()+' 星期'+'日一二三四五六'.charAt(new Date().getDay ())",1000)
</script>
</body>
</html>