Last active
December 18, 2015 13:48
-
-
Save dreamsky/5792274 to your computer and use it in GitHub Desktop.
时间差计算
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function DateDiff(interval, date1, date2) { | |
var longl = date2.getTime() - date1.getTime(); //相差毫秒 | |
switch (interval.toLowerCase()) { | |
case "y": | |
return parseInt(date2.getFullYear() - date1.getFullYear()); | |
case "m": | |
return parseInt((date2.getFullYear() - date1.getFullYear()) * 12 + (date2.getMonth() - date1.getMonth())); | |
case "d": | |
return parseInt(longl / 1000 / 60 / 60 / 24); | |
case "w": | |
return parseInt(longl / 1000 / 60 / 60 / 24 / 7); | |
case "h": | |
return parseInt(longl / 1000 / 60 / 60); | |
case "n": | |
return parseInt(longl / 1000 / 60); | |
case "s": | |
return parseInt(longl / 1000); | |
case "l": | |
return parseInt(longl); | |
} | |
} | |
function getDateDiff(date1, date2) { | |
var dic = { | |
'd': '天前', | |
'h': '小时前', | |
'n': '分钟前', | |
's': '刚刚' | |
}; | |
for(var k in dic){ | |
var diff = DateDiff(k, date1, date2); | |
if(diff){ | |
if(k == 's') { | |
return dic[k]; | |
} | |
else if(k == 'd' && diff > 30) { | |
return Math.floor(diff/30) + '个月前'; | |
} else { | |
return diff + dic[k]; | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment