Date日期对象的使用及格式化

1.获取当前年月日时分秒

// 获取当前时间(getMonth()返回的是当前月(0-11),getDay()获取星期几(周日0,周六 6))
export function getCurrentTime() {
	var date = new Date(),
		Y = date.getFullYear() + "-",
		M = (date.getMonth() + 1 < 10 ? "0" + (date.getMonth() + 1) : date.getMonth() + 1) + "-",
		D = (date.getDate() < 10 ? "0" + date.getDate() : date.getDate()) + " ",
		h = (date.getHours() < 10 ? "0" + date.getHours() : date.getHours()) + ":",
		m = (date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes()) + ":",
		s = date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds();
	// console.log(Y+M+D+h+m+s);
	var getTime = Y + M + D + h + m + s;
	return getTime;
}

2.获取Date总的毫秒数(时间戳)

	//获取Date总的毫秒数,并不是当前时间的毫秒数,而是距离特定时间过了多少毫秒数
	//1.通过 valueOf()或者 getTime()
	var date = new Date();
	console.log(date.valueOf());//现在的时间距离特定时间总的毫秒数
	console.log(date.getTime());
	//2.简单写法
	var dateValue = +new Date();// 返回的就是总的毫秒数
	console.log(dateValue);
	//3.H5新增的 获取总的毫秒数
	console.log(Date.now());

3.获取倒计时(时间戳)

// 倒计时方法
export function countDown(time) {
	const nowTime = +new Date(); //返回的是当前时间总的毫秒数
	const inputTime = +new Date(time); //返回的是用户输入时间总的毫秒数
	const times = (inputTime - nowTime) / 1000; //times是剩余时间总的秒数
	var d = parseInt(times / 60 / 60 / 24); //天
	d = d < 10 ? '0' + d : d
	var h = parseInt(times / 60 / 60 % 24) //时;
	h = h < 10 ? '0' + h : h
	var m = parseInt(times / 60 % 60); //分
	m = m < 10 ? '0' + m : m
	var s = parseInt(times % 60); //当前秒
	s = s < 10 ? '0' + s : s
	const countTime = d + '天' + h + '时' + m + '分' + s + '秒'
	return countTime
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值