Js 之获取几秒、几分钟、几小时、几天前
一、代码
/** * 获取几秒、几分钟、几小时、几天前 * @param time * @returns {string} */ function getDiffTime(time) { var nowTime = parseInt((new Date().getTime()) / 1000); var date = new Date(time * 1000); var year = date.getFullYear(); var month = date.getMonth() + 1; var day = date.getDay(); var hour = date.getHours(); var minute = date.getMinutes(); var second = date.getSeconds(); if(month < 10) { month = '0' + month; } if(day < 10) { day = '0' + day; } if(hour < 10) { hour = '0' + hour; } if(minute < 10) { minute = '0' + minute; } if(second < 10) { second = '0' + second; } var diff = nowTime - time; var diff_day = parseInt(diff / 86400); var diff_hour = parseInt(diff / 3600); var diff_minute = parseInt(diff / 60); var diff_second = parseInt(diff); if(diff_day > 0 && diff_day <= 3) { return diff_day + '天前'; } else if(diff_hour > 0 && diff_day <= 0) { return diff_hour + '小时前'; }else if(diff_hour <= 0 && diff_minute > 0) { return diff_minute + '分钟前'; }else if(diff_second < 60){ if(diff_second <= 0) { return '刚刚'; }else{ return diff_second + '秒前'; } }else if(diff_day >= 3 && diff_day < 30){ return month + '-' + day + ' ' + hour + ':' + minute; }else if(diff_day > 30){ return year + '-' + month + '-' + day + ' ' + hour + ':' + minute + ':' + second; } }