Skip to content

Instantly share code, notes, and snippets.

@dreamsky
Last active December 18, 2015 13:48
Show Gist options
  • Save dreamsky/5792274 to your computer and use it in GitHub Desktop.
Save dreamsky/5792274 to your computer and use it in GitHub Desktop.
时间差计算
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