function timeago(dateTimeStamp){
var minute = 1000 * 60 //把分,时,天,周,半个月,一个月用毫秒表示
var hour = minute * 60
var day = hour * 24
var week = day * 7
var halfamonth = day * 15
var month = day * 30
var now = new Date().getTime() //获取当前时间毫秒
console.log(now)
var diffValue = now - dateTimeStamp//时间差
if(diffValue <0){
return
}
var minC = diffValue/minute //计算时间差的分,时,天,周,月
var hourC = diffValue/hour
var dayC = diffValue/day
var weekC = diffValue/week
var monthC = diffValue/month
if(monthC >= 1 &&monthC <= 3){
result = " " + parseInt(monthC) + "月前"
}else if(weekC >= 1 &&weekC <= 3){
result = " " + parseInt(weekC) + "周前"
}else if(dayC >= 1 &&dayC <= 6){
result = " " + parseInt(dayC) + "天前"
}else if(hourC >= 1 &&hourC <= 23){
result = " " + parseInt(hourC) + "小时前"
}else if(minC >= 1 &&minC <= 59){
result =" " + parseInt(minC) + "分钟前"
}else if(diffValue >= 0 &&diffValue <= minute){
result = "刚刚"
}else {
var datetime = new Date()
datetime.setTime(dateTimeStamp)
var Nyear = datetime.getFullYear()
var Nmonth = datetime.getMonth() + 1 <10 ? "0" + (datetime.getMonth() + 1) : datetime.getMonth() + 1
var Ndate = datetime.getDate() <10 ? "0" + datetime.getDate() : datetime.getDate()
var Nhour = datetime.getHours() <10 ? "0" + datetime.getHours() : datetime.getHours()
var Nminute = datetime.getMinutes() <10 ? "0" + datetime.getMinutes() : datetime.getMinutes()
var Nsecond = datetime.getSeconds() <10 ? "0" + datetime.getSeconds() : datetime.getSeconds()
result = Nyear + "-" + Nmonth + "-" + Ndate
}
return result
}
html不写了,给你js代码自己弄下吧var a1 = '20:20:20'
var a2 = '15:30'
var a3 = '8:10'
var a4 = getSecond(a1) + getSecond(a2)
var a5 = a4 - getSecond(a3)
var a6 = a4>a5 ? a5 : a4
alert( getTime(a4) )
alert( getTime(a5) )
alert( getTime(a6) )
function getSecond(time) {
var timea = time.split(':')
var sec = 0
var j = 0
for(var i=timea.length-1i>=0i--) {//反过来循环
sec = sec + parseInt(timea[i]) * Math.pow(60,j++)
}
return sec
}
function getTime(sec) {
var d = new Date(sec)
var h = Math.floor(sec/3600)
var m = Math.floor( (sec-h*3600)/60 )
var s = sec - h*3600 - m* 60
return h+':'+m+':'+s
}
这两句有问题,Date对象不能这样相减吧?var diffTime= (nowTime - checkDate)/thesecond
diffTime=0-diffTime
应该这样
var diffTime =nowTime.getTime() - checkDate.getTime()
得到差值后,判断正负这些就不多说了,说一下怎么获得这个差值是多少天、小时、分钟和秒。
注:下面的dTime是 new Date(diffTime)
天数可以用你上面的方法计算得到,不过你那方法没有取整。取整的话,就是这样:
var dDays = parseInt(dTime.getTime() / 3600 * 24 * 1000)
然后就剩下时分秒了,我们注意到,new Date(0)是"Thu Jan 01 1970 08:00:00 GMT+0800",所以再减去八个钟就是 1970年1月1日 零时了。所以将上面的diffTime减去八个钟的毫秒数再放到new Date()里面,再获取到的时分秒就是剩余的时间了:
var dHours = dTime.getHours()
var dMinutes =dTime.getMinutes()
var dSeconds = dTime.getSeconds()
你可以看下我的另一个回答
http://zhidao.baidu.com/question/135976703.html