1.js日期格式化
描述:将日期格式化为自己想要的格式,yyyy-MM-dd hh:mm:ss 表示 2020-10-29 09:00:00
参数1:需要转换的日期,Date类型或yyyy-MM-dd hh:mm:ss相关格式或时间戳,默认new Date()
参数2:需要返回的时间格式,默认yyyy-MM-dd
function dateFormat(date = new Date(), formated = "yyyy-MM-dd") {
let currentDate = new Date(date);
let options = {
"y+": currentDate.getFullYear().toString(), // year
"M+": (currentDate.getMonth() + 1).toString(), // month
"d+": currentDate.getDate().toString(), // day
"h+": currentDate.getHours().toString(), // hour
"m+": currentDate.getMinutes().toString(), // minute
"s+": currentDate.getSeconds().toString() // second
};
for (let k in options) {
let ret = new RegExp("(" + k + ")").exec(formated);
if (ret) {
formated = formated.replace(
ret[1],
ret[1].length == 1
? options[k]
: options[k].padStart(ret[1].length, "0")
);
}
}
return formated;
}
2.使用方法
let date = dateFormat();
console.log(date);
输出: 2020-10-29
3.更多日期方法
npm包:npm install date-formatter-js
GitHub:https://github.com/colintaochen/date-formatter-js.git
Gitee:https://gitee.com/colintaochen/date-formatter-js