JS如何获取当前系统时间

JavaScript011

JS如何获取当前系统时间,第1张

系统时间一般是值服务端时间,js获取服务端时间的方法是直接用ajax获取。

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)

不一样。

不同的设备,本地的系统时间是不一样的,假如你电脑设定的时间是9:00那么js获取的就是9:00但是如果此时别人的电脑时间是10:00在别人的电脑上js获取的时间就是10:00。

s是客服端脚本,是不能直接获取服务器端的时间的,除非你用asp,或者jsp,php,等写一个动态的js脚本。

给获取时间定义的一个获取时间方法,在该方法内去获取

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

}