时间转换成距离现在有多久

下面的方法用来把时间转换成距离现在有多久,如几分钟前、几小时前。

需要传入过去的时间,调用示例:
timeFromNow(‘2019/6/13 8:15:00’)
timeFromNow(‘2019-6-13 8:15:00’)
timeFromNow(‘2019-06-13 8:15:00’)
timeFromNow(‘2019,6,13 8:15:00’)
timeFromNow(1560324120000)

function timeFromNow (oldTime){
    if (!oldTime) {
        return false;
    }debugger;
	typeof oldTime === 'string' ? oldTime = oldTime.replace(/-/g, '/') : '';
    var createDay = new Date(oldTime);
    var times = createDay.getTime();
    var nowTime = Date.now();
    var nowDay = new Date();
    var diff = nowTime - times;
	if (diff < 0) {
		throw Error('ERROR:时间不是过去的时间');
	}
    var minute = diff/60/1000; // 分
    var hour = diff/60/60/1000; // 时
    var str='';
    var createYear = createDay.getFullYear();
    var createMonth = createDay.getMonth() + 1 > 9 ? createDay.getMonth() + 1 : '0' + (createDay.getMonth() + 1);
    var createHours = createDay.getHours() > 9 ? createDay.getHours() : ('0' + createDay.getHours());
    var createMinute = createDay.getMinutes() > 9 ? createDay.getMinutes() : ('0' + createDay.getMinutes());
    var createDate = createDay.getDate() > 9 ? createDay.getDate() : ('0' + createDay.getDate());
    var createDayFormat = createYear + '/' + createMonth + '/' + createDate;

    var nowYear = nowDay.getFullYear();
    var nowMonth = nowDay.getMonth() + 1 > 9 ? nowDay.getMonth() + 1 : '0' + (nowDay.getMonth() + 1);
    var nowDate = nowDay.getDate();
    var nowDayFormat = nowYear + '/' + nowMonth + '/' + nowDate;

    var diffDay = (new Date(nowDayFormat).getTime() - new Date(createDayFormat).getTime()) / 1000 / 60 / 60 / 24; // 现在与创建时间的差值:天
    var arr = ['刚刚', '分钟前', '小时前', '昨天 ', '前天 '];
    if (nowYear - createYear == 0) { // 在本年内
        if (diffDay === 0) { // 今天
            if (parseInt(minute) < 1) {
                str = arr[0];
            } else if (minute >= 1) {
                str = (parseInt(minute) || 1) + arr[1];
            } else if (hour >= 1) {
                str = parseInt(hour) + arr[2];
            } 
        } else if (diffDay === 1) { // 昨天
            str = arr[3] + createHours + ':' + createMinute;
        } else if (diffDay === 2) { // 前天
            str = arr[4] + createHours + ':' + createMinute;
        } else if (diffDay > 2) { // 很多天前
            str = createMonth + '-' + createDate + ' ' + createHours + ':' +createMinute;
        }
    } else if (nowYear - createYear > 0) { // 不在本年度内容
        str = createYear + '-' + createMonth + '-' + createDate + ' ' + createHours + ':' + createMinute;
    }
    return str;
}

你可能感兴趣的:(日期,js,小玩意)