js 将long型字符串转换成日期格式
工作中难免会碰到日期的转换,往往为了方便,后台都是把时间以long型(形如1343818800000)返回给web前端.再有前端自己根据页面需求转换成相应的日期格式.这里将我常用的一个转换时间的函数贴上:
//转换时间函数
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型为日期字符串
function getFormatDateByLong(l, pattern) {
return getFormatDate(new Date(l), pattern);
}
//转换日期对象为日期字符串
function getFormatDate(date, pattern) {
if (date == undefined) {
date = new Date();
}
if (pattern == undefined) {
pattern = "yyyy-MM-dd hh:mm:ss";
}
return date.format(pattern);
}
function getSmpFormatDate(date, isFull) {
var pattern = "";
if (isFull == true || isFull == undefined) {
pattern = "yyyy-MM-dd hh:mm:ss";
} else if(isFull==2){
pattern = "yyyy-MM-dd hh:mm";
}
else {
pattern = "yyyy-MM-dd";
}
return getFormatDate(date, pattern);
}
function getSmpFormatDateByLong(date, isFull) {
if(date=='' || date==null){
return
}
return getSmpFormatDate(new Date(date), isFull);
}
你的眼界 不止于此