// 格式化时间
function formatDateTime(dateTime) {
const year = dateTime.getFullYear();
const month = dateTime.getMonth() + 1 < 10 ? '0' + (dateTime.getMonth() + 1) : dateTime.getMonth() + 1;
const date = dateTime.getDate() < 10 ? '0' + dateTime.getDate() : dateTime.getDate();
const hours = dateTime.getHours() < 10 ? '0' + dateTime.getHours() : dateTime.getHours();
const minutes = dateTime.getMinutes() < 10 ? '0' + dateTime.getMinutes() : dateTime.getMinutes();
const seconds = dateTime.getSeconds() < 10 ? '0' + dateTime.getSeconds() : dateTime.getSeconds();
// 2022/04/21 17:16:03
return (year + '/' + month + '/' + date + ' ' + hours + ':' + minutes + ':' + seconds);
}
简化写法:
let now = new Date();
// 'PRC'(People Republic of China): 中国大陆时区, 不区分大小写.
// '2-digit': 如果为 10 以下则在前面加 0. 只有 month, day 需为 '2-digit'
const options = {
timeZone: 'PRC',
year: 'numeric', month: '2-digit', day: '2-digit',
hour: 'numeric', minute: 'numeric', second: 'numeric'
};
// locales: 'zh-CN' 不区分大小写.
now = now.toLocaleString('zh-CN', options);
console.log(now);
// 2022/04/21 17:16:03
官方文档
toLocaleString(locales?: string | string[], options?: Intl.DateTimeFormatOptions): string;
DateTimeFormatOptions 接口
interface DateTimeFormatOptions {
localeMatcher?: "best fit" | "lookup" | undefined;
weekday?: "long" | "short" | "narrow" | undefined;
era?: "long" | "short" | "narrow" | undefined;
year?: "numeric" | "2-digit" | undefined;
month?: "numeric" | "2-digit" | "long" | "short" | "narrow" | undefined;
day?: "numeric" | "2-digit" | undefined;
hour?: "numeric" | "2-digit" | undefined;
minute?: "numeric" | "2-digit" | undefined;
second?: "numeric" | "2-digit" | undefined;
timeZoneName?: "long" | "short" | undefined;
formatMatcher?: "best fit" | "basic" | undefined;
hour12?: boolean | undefined;
timeZone?: string | undefined;
}