
格式化日期时间主要功能特点:
1、传入要格式化的时间,可以是时间戳、日期、日期时间;
2、如传递是日期格式那会自动转换成时间戳;
3、可以格式化成任意格式,比如:Y年m月d日 H时i分s秒、d/m、m/Y、H:i:s等格式;
4、如不传任何参数,那么默认为当前时间和Y-m-d格式。
代码如下:
//格式化时间,timestamp=时间戳或日期时间,formats=日期格式,默认Y-m-d
function formatDate(timestamp, formats) {
let timestampRegex = /^(\d{13}|\d{10})$/;
timestamp=timestamp || (new Date()).valueOf(); formats = formats || 'Y-m-d';
if(timestampRegex.test(timestamp)){
if(timestamp.toString().length==10){ timestamp=timestamp * 1000; }
}else if(!isNaN(Date.parse(timestamp))){
timestamp=new Date(timestamp).getTime();
}
let date = new Date(timestamp),
year = date.getFullYear(),
month = ("0" + (date.getMonth() + 1)).slice(-2),
day = ("0" + date.getDate()).slice(-2),
hour = ("0" + date.getHours()).slice(-2),
minute = ("0" + date.getMinutes()).slice(-2),
second = ("0" + date.getSeconds()).slice(-2);
return formats.replace(/Y|m|d|H|i|s/ig, function (matches) {
return ({ Y:year, m:month, d:day, H:hour, i:minute, s:second })[matches];
});
}
上一篇:SmartPhoto手机/电脑端查看图片插件使用说明文档
讨论数量:0