js日期格式化7天前起止日期以及YYYY-MM-DD 原生实现

这篇博客探讨了JavaScript中日期格式化的多种方法,包括使用Intl.DateTimeFormat和Date对象的toLocaleString方法。示例代码展示了如何将日期转换为'YYYY-MM-DD'格式,并获取七天前的日期范围。此外,还提到了日期到JSON的转换方法及其相关属性的使用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


// YYYY-MM-DD 原生实现

console.log(Intl.DateTimeFormat("zh", { separator: "-", dateStyle: "short", timeStyle: "medium", }).format(),'DateTimeFormat',)




日期转json
console.log(today.toString());  //Mon Nov 11 2019 11:19:12 GMT+0800 (中国标准时间)
console.log(today.toISOString());  //2019-11-11T03:19:12.534Z
console.log(today.toTimeString());  //11:19:12 GMT+0800 (中国标准时间)
console.log(today.toUTCString());  //Mon, 11 Nov 2019 03:19:12 GMT
console.log(today.toLocaleDateString());  //2019/11/11
console.log(today.toLocaleString());        //2019/11/11 上午11:19:12
console.log(today.toLocaleString('chinese',{hour12:false}));        //2019/12/11 14:17:18
console.log(today.toLocaleTimeString());  //上午11:19:12
export const getData_YYYMMDD = (howLongDayAgo: number, type?: 'month',justYYYYDD?:boolean): string => {

	const currentDate = new Date();
	if(howLongDayAgo){
		if (type==='month') {
			
			
			currentDate.setMonth(currentDate.getMonth() - howLongDayAgo);
		} else {
			currentDate.setDate(currentDate.getDate() - howLongDayAgo);
				
		}
	}
	const options: {
    	year: string;
    	month: string;
    	day?: string;
	} = { year: 'numeric', month: '2-digit', day: '2-digit' };
	if (justYYYYDD) {
		delete options.day
	}
	return currentDate.toLocaleDateString('en-CA', options); // 使用加拿大英语格式
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值