代码如下:
参数:
t: 时间戳, type:返回格式(1:IM界面,其他:会话列表)
function formartTime(t, type) {
var oldtime = new Date(t);
var date = new Date();
var today = new Date(date.getFullYear(), date.getMonth(), date.getDate()).getTime(); //今天凌晨
var yestday = new Date(today - 24 * 3600 * 1000).getTime();
var beforeYestday = new Date(today - 24 * 3600 * 1000 * 2).getTime();
var beforeWeek = new Date(today - 24 * 3600 * 1000 * 7).getTime();
var Y = oldtime.getFullYear(); //年份
var M = oldtime.getMonth() + 1; //月份
var d = oldtime.getDate(); //日
var h = oldtime.getHours() % 12 == 0 ? 12 : oldtime.getHours() % 12; //12小时
var H = oldtime.getHours(); //24小时
var m = oldtime.getMinutes(); //分
var w = toWeek(oldtime.getUTCDay()); //星期
var timesolt = toTimeSolt(oldtime.getHours()); //时间段 timeStr = ''; //当天
if (oldtime.getTime() > yestday) {
timeStr = H + ':' + m;
}
//昨天
if (oldtime.getTime() < today && yestday <= oldtime.getTime()) {
timeStr = '昨天 ' + (type == 1 ? H + ':' + m : '');
}
// 一周内
if (oldtime.getTime() < yestday && beforeWeek <= oldtime.getTime()) {
timeStr = w + (type == 1 ? ' ' + H + ':' + m : '');
}
// 一周前
if (oldtime.getTime() < beforeWeek) {
timeStr = type == 1 ? Y + '年' + M + '月' + d + '日 ' + timesolt + ' ' + H + ':' + m : Y + '/' + M + '/' + d;
}
// 比当前时间晚
if (oldtime.getTime() > date.getTime()) {
timeStr = '手动修改';
} // 格式化时间段
function toTimeSolt(h) {
var bt = '';
if (0 <= h && h <= 3)
bt = '凌晨';
if (4 <= h && h <= 8)
bt = '早上';
if (9 <= h && h <= 11)
bt = '上午';
if (12 == h)
bt = '中午';
if (13 <= h && h <= 17)
bt = '下午';
if (18 <= h && h <= 23)
bt = '晚上'; return bt;
} // 格式星期
function toWeek(w) {
var week = '';
switch (w) {
case 0:
week = '星期日';
break;
case 1:
week = '星期一';
break;
case 2:
week = '星期二';
break;
case 3:
week = '星期三';
break;
case 4:
week = '星期四';
break;
case 5:
week = '星期五';
break;
case 6:
week = '星期六';
break;
}
return week;
}
return timeStr;
}
使用:
formartTime('1512230340000', 1)