封装一个时间戳

//补零
function doHandleMonth(month) {
	var m = month;
	if (month.toString().length == 1) {
		m = "0" + month;
	}
	return m;
}
 

// 近X天
export function getDay(day) {
	var today = new Date();
	var targetday_milliseconds = today.getTime() + 1000 * 60 * 60 * 24 * day;
	today.setTime(targetday_milliseconds);
	var tYear = today.getFullYear();
	var tMonth = today.getMonth();
	var tDate = today.getDate();
	let tHour = doHandleMonth(today.getHours()) // 时
	let tMin = doHandleMonth(today.getMinutes()) // 分
	let tSed = doHandleMonth(today.getSeconds())
	tMonth = doHandleMonth(tMonth + 1);
	tDate = doHandleMonth(tDate);
	// return tYear + "-" + tMonth + "-" + tDate;
	return (`${tYear}-${tMonth}-${tDate} ${tHour}:${tMin}:${tSed}`)
}
// 本月
export function getNowMonth() {
	var today = new Date();
	var tYear = today.getFullYear();
	var tMonth = today.getMonth();
	var tDate = today.getDate();
	tMonth = doHandleMonth(tMonth + 1);
	tDate = "01"
	return tYear + "-" + tMonth + "-" + tDate;
}
 
// 上月日期
export function getLastMonth() {
	const date = new Date()
	const year = date.getFullYear()
	const month = date.getMonth()
	const lastMonthStartDate = formatDate(new Date(year, month - 1, 1))
	const lastMonthEndDate = formatDate(new Date(year, month, 0))
	const lastMonth = []
	lastMonth.push(lastMonthStartDate, lastMonthEndDate)
	return lastMonth
}

export function formatDate(dateTime = null, fmt = 'yyyy-mm-dd') {
	// 如果为null,则格式化当前时间
	if (!dateTime) dateTime = Number(new Date())
	// 如果dateTime长度为10或者13,则为秒和毫秒的时间戳,如果超过13位,则为其他的时间格式
	if (dateTime.toString().length == 10) dateTime *= 1000;
	let date = new Date(dateTime);
	let ret;
	let opt = {
		"y+": date.getFullYear().toString(), // 年
		"m+": (date.getMonth() + 1).toString(), // 月
		"d+": date.getDate().toString(), // 日
		"h+": date.getHours().toString(), // 时
		"M+": date.getMinutes().toString(), // 分
		"s+": date.getSeconds().toString() // 秒
		// 有其他格式化字符需求可以继续添加,必须转化成字符串
	};
	for (let k in opt) {
		ret = new RegExp("(" + k + ")").exec(fmt)
		if (ret) {
			fmt = fmt.replace(ret[1], (ret[1].length == 1) ? (opt[k]) : (opt[k].padStart(ret[1].length, "0")))
		}
	}
	return fmt
}

在页面中调用 this.formData.timeon = formatDate(getDay(0), "yyyy-mm-dd hh:MM:ss");

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值