JS 获取当前时间日期、昨日、明日日期的格式化工具类(直接拿去使用)

昨日、明日日期的工具类:

获取明日的日期

//定义
const formatDateTomorrow  = date => {
	function formatDate(date) {
		let year = date.getFullYear();
		let month = date.getMonth() + 1;
		let day = date.getDate();
		if (month < 10) {
			month = '0' + month;
		}
		if (day < 10) {
			day = '0' + day;
		}
		return year + '-' + month + '-' + day;
	}

	const today = new Date();
	const tomorrow = new Date(today);
	tomorrow.setDate(tomorrow.getDate() + 1);
	return formatDate(tomorrow)
}
//调用
let tomorrowDate = formatDateTomorrow(new Date())//当前日期的明日日期;
//可推算具体日期的第二天
let tomorrowDate = formatDateTomorrow(new Date('2024-1-31'))//2024-02-01;

获取昨日的日期(同理)

//定义
const formatDateToYesterday = date => {
	function formatDate(date) {
		let year = date.getFullYear();
		let month = date.getMonth() + 1;
		let day = date.getDate();
		if (month < 10) {
			month = '0' + month;
		}
		if (day < 10) {
			day = '0' + day;
		}
		return year + '-' + month + '-' + day;
	}

	const today = new Date();
	const yesterday= new Date(today);
	yesterday.setDate(yesterday.getDate() - 1);
	return formatDate(yesterday)
}
//调用
let yesterdayDate = formatDateYesterday(new Date())//当前日期的昨日日日期;
//可推算具体日期的第二天
let yesterdayDate = formatDateYesterday(new Date('2024-1-31'))//2024-01-30;

时间格式化工具类

//定义
const formatDate = date => {
	const year = date.getFullYear()
	const month = date.getMonth() + 1
	const day = date.getDate()
	return [year, month, day].map(formatNumber).join('-')
}
const formatNumber = n => {
	n = n.toString()
	return n[1] ? n : '0' + n
}
//调用
let newDate = formatDate(new Date()) // 2024-01-31

日期时间格式化工具类

//定义
const formatTime = date => {
	const year = date.getFullYear()
	const month = date.getMonth() + 1
	const day = date.getDate()
	const hour = date.getHours()
	const minute = date.getMinutes()
	const second = date.getSeconds()
	return [year, month, day].map(formatNumber).join('-') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}
const formatNumber = n => {
	n = n.toString()
	return n[1] ? n : '0' + n
}
//调用
let newDate = formatDate(new Date()) // 2024-01-31 09:22:45

你可能感兴趣的:(CSS,JS),javascript,开发语言)