最近在项目中遇到一个时间格式转换的要求。
转换规则
- 如果时间戳(下文中提到的时间戳都指向要转换的时间戳)在今天,则返回的格式为 “HH:mm:ss”
- 如果时间戳在昨天,则返回的格式为 “昨天 HH:mm:ss”
- 如果时间戳在本周内并且非昨天,假如说在周一,则返回的格式为 “周一 HH:mm:ss”
- 如果时间戳在本年内并非一周内,假如说在1月12日,则返回的格式为 “01月12日 HH:mm:ss”
- 如果时间戳在今年以前的日期内,则返回的格式为 “yyyy年MM月dd日 HH:mm:ss”
例子
在网上也有看到的一些,但具体和规则有些出入,所以就自己写了一个,可以先点击此处体验一下:查看
代码
function timeChangeFormat(timeObj) {
timeObj = timeObj * 1;
var curTime = new Date().getTime(); // 当前时间戳
var curTimeMinutes = parseInt(curTime / 1000 / 60); //当前时间分钟数
var timeObjMinutes = parseInt(timeObj / 1000 / 60); //参数时间分钟数
var timeDifference = curTimeMinutes - timeObjMinutes; // 参数时间戳与当前时间戳相差分钟
var curDate = new Date(curTime); // 当前时间日期对象
var timeObjDate = new Date(timeObj); // 参数时间戳转换成的日期对象
var timeYear = timeObjDate.getFullYear(),
timeMonth = timeObjDate.getMonth() + 1,
timeDate = timeObjDate.getDate(),
timeDay = timeObjDate.getDay(),
timeHour = timeObjDate.getHours(),
timeMinutes = timeObjDate.getMinutes(),
timeSeconds = timeObjDate.getSeconds();
var weekDayText = ["星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"];
// 补0操作
function addZero(num) {
return (String(num).length == 1 ? '0' : '') + num;
}
// 转换的时间戳是否与当前时间在同一周,是返回true,否则false
function isSameWeek(curDate, timeDifference) {
var day = curDate.getDay() - 1;
var hour = curDate.getHours();
var minutes = curDate.getMinutes();
var weekMinutes = day * 24 * 60 + hour * 60 + minutes; // 从当前时间算起已经过去多少分钟了
if (timeDifference <= weekMinutes) {
return true;
} else {
return false;
}
}
if (curDate.getFullYear() == timeYear && curDate.getMonth() + 1 == timeMonth && curDate.getDate() == timeDate) {
return addZero(timeHour) + ':' + addZero(timeMinutes) + ':' + addZero(timeSeconds);
} else {
var newDate = new Date((curTimeMinutes - 1440) * 60 * 1000);
if (newDate.getFullYear() == timeYear && newDate.getMonth() + 1 == timeMonth && newDate.getDate() == timeDate) {
return '昨天 ' + addZero(timeHour) + ':' + addZero(timeMinutes) + ':' + addZero(timeSeconds);
} else if (isSameWeek(curDate, timeDifference)) {
return weekDayText[timeDay] + ' ' + addZero(timeHour) + ':' + addZero(timeMinutes) + ':' + addZero(timeSeconds);
} else if (curDate.getFullYear() == timeYear) {
return addZero(timeMonth) + '月' + addZero(timeDate) + '日 ' + addZero(timeHour) + ':' + addZero(timeMinutes) + ':' + addZero(timeSeconds);
} else {
return timeYear + '年' + addZero(timeMonth) + '月' + addZero(timeDate) + '日 ' + addZero(timeHour) + ':' + addZero(timeMinutes) + ':' + addZero(timeSeconds);
}
}
}
参数说明
函数的参数为一个毫秒级的时间戳。