Skip to content

Instantly share code, notes, and snippets.

@JSoon
Last active January 30, 2018 06:13
Show Gist options
  • Save JSoon/c28390599a556a15d4f1f72450c42eee to your computer and use it in GitHub Desktop.
Save JSoon/c28390599a556a15d4f1f72450c42eee to your computer and use it in GitHub Desktop.
时间差函数
'use strict';
/**
* 编写timeAgo(t1,t2) 函数
* 不用考虑闰年情况
* 完成以下应该的输出
timeAgo('2016-01-01','2017-02-01') //1年前
timeAgo('2016-01-01','2016-03-01') //2个月前
timeAgo('2016-01-01','2016-01-16') //15天前
timeAgo('2016-01-01','2016-01-01T01:13:01') //1小时前
timeAgo('2016-01-01','2016-01-01T00:13:01') //13分钟前
timeAgo('2016-01-01','2016-01-01T00:00:50') //50秒前
timeAgo('2018-01-01','2017-01-01') //1年后
timeAgo('2016-03-01','2016-01-01') //2个月后
timeAgo('2016-01-16','2016-01-01') //15天后
timeAgo('2016-01-01T01:13:01','2016-01-01') //1小时后
timeAgo('2016-01-01T00:13:01','2016-01-01') //13分钟后
timeAgo('2016-01-01T00:00:50','2016-01-01') //50秒后
*/
const timeAgo = function(t1, t2) { //两个时间差 中文显示函数
t1 = new Date(t1);
t2 = new Date(t2);
var t = t1 - t2;
if(t === 0) { return 0; }
var s = (t > 0 ? (t1 - t2) : (t2 - t1))/1000;
var boa = t > 0 ? '后' : '前';
var m = s/60;
var h = m/60;
var d = h/24;
var M = d/30;
var y = d/365;
var diff;
y < 1 && M < 1 && d < 1 && h < 1 && m < 1 && (diff = Math.round(s) + '秒');
y < 1 && M < 1 && d < 1 && h < 1 && m >= 1 && (diff = Math.round(m) + '分钟');
y < 1 && M < 1 && d < 1 && h >= 1 && (diff = Math.round(h) + '小时');
y < 1 && M < 1 && d >= 1 && (diff = Math.round(d) + '天');
y < 1 && M >= 1 && (diff = Math.round(M) + '个月');
y >=1 && (diff = Math.round(y) + '年');
return diff + boa;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment