给定long型时间戳,js判断改时间节点,返回今天、昨天、前天或自定义日期形式:
//扩展Date的format方法 Date.prototype.format = function (format) { var o = { "M+": this.getMonth() + 1, "d+": this.getDate(), "h+": this.getHours(), "m+": this.getMinutes(), "s+": this.getSeconds(), "q+": Math.floor((this.getMonth() + 3) / 3), "S": this.getMilliseconds() } if (/(y+)/.test(format)) { format = format.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length)); } for (var k in o) { if (new RegExp("(" + k + ")").test(format)) { format = format.replace(RegExp.$1, RegExp.$1.length == 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length)); } } return format; }; /* 转换long值为日期字符串 * l long值 * pattern 格式字符串,例如:yyyy-MM-dd hh:mm:ss */ function getFormatDateByLong(l, pattern) { return getFormatDate(new Date(l), pattern); }; function getFormatDate(date, pattern) { if (date == undefined) { date = new Date(); } if (pattern == undefined || pattern == "") { pattern = "yyyy-MM-dd hh:mm:ss"; } return date.format(pattern); }; //时间格式转换 function returnDiyDate(date) { //date = parseInt(date); //强转整型 var tDate = getFormatDate(new Date(), "yyyy/MM/dd"); //当前凌晨时间(string) var tTime = new Date(tDate).getTime(); //当前凌晨时间(long) var eTime = 24 * 60 * 60 * 1000; //一天时间(long) var yTime = tTime - eTime; //昨天凌晨时间(long) var byTime = tTime - 2 * eTime; //前天凌晨时间(long) var formatDate = getFormatDateByLong(date, "hh:mm"); //转成时分格式 if (date >= tTime) { //今天 var result = formatDate; } else if (date < tTime && date >= yTime) { //昨天 var result = "昨天 " + formatDate; } else if (date < yTime && date >= byTime) { //前天 var result = "前天 " + formatDate; } else { //前天之前 var result = getFormatDateByLong(date, "MM-dd hh:mm"); } return result; };
调用示例:
var l = 1405042645000; returnDiyDate(l);