var startTime = Math.ceil(new Date().getTime()/1000)//单位秒
var play_time = ""
//获取视频标签播发时间
$('#video-active').on("timeupdate",function(event){
var all_time = this.duration
play_time = this.currentTime
})
//初始化时间
getDuration = function(){
var time = '',
hours = 0,
minutes = 0,
seconds = 0,
endTime = Math.ceil(new Date().getTime()/1000),
duration = endTime - startTime
if(play_time){
duration = play_time
}
// var g_time = ""
var dt = localStorage.getItem("param")
if(dt == null || dt == "" || dt == undefined){
localStorage.setItem("param", duration)
// data = param
}else{
duration = duration + parseInt(dt)
}
localStorage.setItem("param", duration)
hours = Math.floor(duration/3600)//停留小时数
minutes = Math.floor(duration%3600/60)//停留分钟数
seconds = Math.floor(duration%3600%60)//停留秒数
time = (hours <10 ? '0' + hours : hours) + ':' + (minutes <10 ? '0' + minutes : minutes) + ':' + (seconds <10 ? '0' + seconds : seconds)
$.ajax({
type: "POST",
url: "url",
data: {time: time,id: id,play_time: play_time},
success: function(data) {
console.log(data)
},
error: function() {
}
})
}
//监听窗口关闭事件
window.onbeforeunload = function(e){
var duration = getDuration()
//request(duration)
}
})()
</script>
系统时间一般是值服务端时间,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)