一、把时间格式化为多少秒、分钟、小时、天、月、年之前
function friendlyDate(timestamp) {
var formats = {
'year': '%n% 年前',
'month': '%n% 月前',
'day': '%n% 天前',
'hour': '%n% 小时前',
'minute': '%n% 分钟前',
'second': '%n% 秒前',
};
var now = Date.now();
var seconds = Math.floor((now - timestamp) / 1000);
var minutes = Math.floor(seconds / 60);
var hours = Math.floor(minutes / 60);
var days = Math.floor(hours / 24);
var months = Math.floor(days / 30);
var years = Math.floor(months / 12);
var diffType = '';
var diffValue = 0;
if (years > 0) {
diffType = 'year';
diffValue = years;
} else {
if (months > 0) {
diffType = 'month';
diffValue = months;
} else {
if (days > 0) {
diffType = 'day';
diffValue = days;
} else {
if (hours > 0) {
diffType = 'hour';
diffValue = hours;
} else {
if (minutes > 0) {
diffType = 'minute';
diffValue = minutes;
} else {
diffType = 'second';
diffValue = seconds === 0 ? (seconds = 1) : seconds;
}
}
}
}
}
return formats[diffType].replace('%n%', diffValue);
}
二、时间格式化以指定格式返回时间(yyyy-MM-dd hh:mm:ss)
function formatDate(dateTime,formatValue){
let timer = new Date(dateTime);
let year = timer.getFullYear();
let month = timer.getMonth()+1;
let date = timer.getDate();
let hour = timer.getHours();
let minute = timer.getMinutes();
let second = timer.getSeconds();
if(month<10)month = "0"+month;
if(date<10)date = "0"+date;
if(hour<10)hour = "0"+hour;
if(minute<10)minute = "0"+minute;
if(second<10)second = "0"+second;
let result = null;
switch(formatValue){
case "yyyy-MM-dd hh:mm:ss": result = year+"-"+month+"-"+date+" "+hour+":"+minute+":"+second;
break;
case "yyyy/MM/dd hh:mm:ss": result = year+"/"+month+"/"+date+" "+hour+":"+minute+":"+second;
break;
case "yyyy-MM-dd": result = year+"-"+month+"-"+date;
break;
case "yyyy/MM/dd": result = year+"/"+month+"/"+date;
break;
case "hh:mm:ss": result = hour+":"+minute+":"+second;
break;
default: result = "格式错误";
}
return result;
}
//console.log(formatDate(new Date,"yyyy-MM-dd hh:mm:ss"));
//console.log(formatDate(new Date,"yyyy/MM/dd hh:mm:ss"));
//console.log(formatDate(new Date,"yyyy-MM-dd"));
//console.log(formatDate(new Date,"yyyy/MM/dd"));
//console.log(formatDate(new Date,"hh:mm:ss"));