-
Notifications
You must be signed in to change notification settings - Fork 0
Open
Description
const formatingTokens = /YYYY|YY|MM?|DD?/g;
const expressions = {
YYYY: {
reg: /\d{4}/,
parse(input) {
this.year = +input;
},
},
YY: {
reg: /\d{2}/,
parse(input) {
this.year = +input + 2000;
},
},
MM: {
reg: /\d{2}/,
parse(input) {
this.month = +input - 1;
},
},
M: {
reg: /\d/,
parse(input) {
this.month = +input - 1;
},
},
DD: {
reg: /\d{2}/,
parse(input) {
this.date = +input;
},
},
};
Date.prototype.format = function(fmt) {
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(fmt)) {
fmt=fmt.replace(RegExp.$1, (this.getFullYear()+"").substr(4 - RegExp.$1.length));
}
for(var k in o) {
if(new RegExp("("+ k +")").test(fmt)){
fmt = fmt.replace(RegExp.$1, (RegExp.$1.length==1) ? (o[k]) : (("00"+ o[k]).substr((""+ o[k]).length)));
}
}
return fmt;
}
function parse(input, format) {
const date = {};
const tokens = format.matchAll(formatingTokens);
for (const token of tokens) {
const str = input.substr(token.index, token[0].length);
expressions[token[0]].parse.call(date, str);
}
console.log(date.year, date.month, date.date);
return new Date(date.year, date.month, date.date, 0, 0, 0);
}
console.log(parse("05-20-2022", "MM-DD-YYYY").toLocaleString());
console.log(parse("05-20-2022", "MM-DD-YYYY").format("yyyy-MM-dd"));Metadata
Metadata
Assignees
Labels
No labels