JS 时间计算

JavaScript014

JS 时间计算,第1张

要下班了没时间了,这两个函数能帮到你

第一个把时间转换为整数,这样你就能去计算了,第二个把数字转换成时间,你可以用来显示了

function getIntFromTime(time) {

time = time.split(':')

return parseInt(time[0], 10) * 60 * 60 + parseInt(time[1], 10) * 60 + parseInt(time[2], 10)

}

function getTimeFromInt(value) {

var h = Math.floor(value / 60 / 60)

var m = value % (60*60)

var s = value % (60)

if (h.toString().length <2) h = '0' + h.toString()

if (m.toString().length <2) m = '0' + m.toString()

if(s.toString().length <2) s = '0' + s.toString()

 return h + ':' + m + ':' + s

}

//dateTimeStamp是一个时间毫秒,注意时间戳是秒的形式,在这个毫秒的基础上除以1000,就是十位数的时间戳。13位数的都是时间毫秒。

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

}

按照你的要求编写的计算时间差的Javascript程序如下(注意 date是随意写的正确的日期字符串,只是为了函数Date.parse()的需要)

<script type=text/javascript>

 var date="2018/07/17"

 var time1 = Date.parse(date+" "+"2:32:39")

 var time2 = Date.parse(date+" "+"14:12:09")

 var time3=time2-time1

 var hour=Math.floor(time3/1000/60/60)

 var minute=Math.floor(time3/1000/60-hour*60)

 var second=time3/1000-hour*60*60-minute*60

 alert("时间差为"+hour+"小时"+minute+"分"+second+"秒")

</script>

运行结果

时间差为11小时39分30秒