感觉@M5的方法还不够通用,每次都需要 new Date(parseInt(1432089477) * 1000) 做一层包装。因为在App开发中,一般接收的是接口传过来的时间戳,所以这里重新设计了方法接口,方便传入时间戳和字符串格式。
/**
* 对日期进行格式化 'yyyy-MM-dd hh:mm:ss'
* @param timestamp 要格式化的时间戳
* @param format 进行格式化的模式字符串
* 支持的模式字母有:
* y:年,
* M:年中的月份(1-12),
* d:月份中的天(1-31),
* h:小时(0-23),
* m:分(0-59),
* s:秒(0-59),
* S:毫秒(0-999),
* q:季度(1-4)
* @return String
*/
function date_format(timestamp, format){
var date = new Date(parseInt(timestamp)*1000).toString();
date = new Date(date);
var map = {
"M": date.getMonth() + 1, //月份
"d": date.getDate(), //日
"h": date.getHours(), //小时
"m": date.getMinutes(), //分
"s": date.getSeconds(), //秒
"q": Math.floor((date.getMonth() + 3) / 3), //季度
"S": date.getMilliseconds() //毫秒
};
format = format.replace(/([yMdhmsqS])+/g, function(all, t){
var v = map[t];
if(v !== undefined){
if(all.length > 1){
v = '0' + v;
v = v.substr(v.length-2);
}
return v;
}
else if(t === 'y'){
return (date.getFullYear() + '').substr(4 - all.length);
}
return all;
});
return format;
}
// 使用方法
date_format(1433124009, 'yyyy-MM-dd hh:ii:ss');
// print 2015-06-01 10:00:09
// 日历控件需要先进行转换,将日期对象转换成时间戳
plus.nativeUI.pickDate(function(event){
var d = event.date;
document.getElementById("begin_date").value = date_format(d.getTime()/1000, 'yyyy-MM-dd');
}, function(e){
// '未选择日期:'+e.message);
});
3 个回复
半杯可乐 - 努力奋斗中。
踩着单车载着猪
自己格式化下~
蔡繁荣 (作者)
谢谢,怎么没想到呢。。。
2015-05-29 15:55
蔡繁荣 (作者) - 发表是最好的记忆
感觉@M5的方法还不够通用,每次都需要 new Date(parseInt(1432089477) * 1000) 做一层包装。因为在App开发中,一般接收的是接口传过来的时间戳,所以这里重新设计了方法接口,方便传入时间戳和字符串格式。