-
-
Notifications
You must be signed in to change notification settings - Fork 230
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
实现日期格式化函数 #95
Comments
function parseTime(time, pattern) {
if (arguments.length === 0 || !time) {
return null
}
const format = pattern || '{y}-{m}-{d} {h}:{i}:{s}'
let date
if (typeof time === 'object') {
date = time
} else {
if ((typeof time === 'string') && (/^[0-9]+$/.test(time))) {
time = parseInt(time)
} else if (typeof time === 'string') {
time = time.replace(new RegExp(/-/gm), '/').replace('T', ' ').replace(new RegExp(/\.[\d]{3}/gm), '');
}
if ((typeof time === 'number') && (time.toString().length === 10)) {
time = time * 1000
}
date = new Date(time)
}
const formatObj = {
y: date.getFullYear(),
m: date.getMonth() + 1,
d: date.getDate(),
h: date.getHours(),
i: date.getMinutes(),
s: date.getSeconds(),
a: date.getDay()
}
const time_str = format.replace(/{(y|m|d|h|i|s|a)+}/g, (result, key) => {
let value = formatObj[key]
// Note: getDay() returns 0 on Sunday
if (key === 'a') {
return ['日', '一', '二', '三', '四', '五', '六'][value]
}
if (result.length > 0 && value < 10) {
value = '0' + value
}
return value || 0
})
return time_str
}
console.log(parseTime(Date.now()));
console.log(parseTime(Date.now(), "{y}-{m}-{d}")); |
|
function formatTime() {
const time = new Date();
const year = time.getFullYear();
const month = time.getMonth() + 1;
const day = time.getDate();
const hour = time.getHours();
const minute = time.getMinutes();
const seconds = time.getSeconds();
return `${year}-${month}-${day} ${hour}:${minute}:${seconds}`;
}
console.log(formatTime()); 最简易版本的,注意 没有加0的版本 |
function formatDate(date, format) {
const pad = (n) => n < 10 ? '0' + n : n;
const dateDict = {
"YYYY": date.getFullYear(),
"MM": pad(date.getMonth() + 1),
"DD": pad(date.getDate()),
"HH": pad(date.getHours()),
"mm": pad(date.getMinutes()),
"ss": pad(date.getSeconds())
};
return format.replace(/(YYYY|MM|DD|HH|mm|ss)/g, matched => dateDict[matched]);
}
let date = new Date();
console.log(formatDate(date, 'YYYY-MM-DD')); // 输出形如 '2023-09-08' 的日期
console.log(formatDate(date, 'YYYY/MM/DD HH:mm:ss')); // 输出形如 '2023/09/08 17:20:04' |
No description provided.
The text was updated successfully, but these errors were encountered: