JavaScript Date toLocaleString() 格式化时间简易写法

本文介绍了如何精简JavaScript的日期格式化函数,将'formatDateTime'方法简化为使用内置的toLocaleString方法,并详细解释了DateTimeFormatOptions接口在时区和格式设置上的应用。
摘要由CSDN通过智能技术生成
// 格式化时间
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;
}

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值