JavaScript时间日期

通过时间日期对象可以从中获取更加具体的时间日期

var date = new Date()
//获取到年
var year = date.getfulYear()
console.log(year)	//当前的年份	2022
//获取月份	0~11来描述月份
var month =date.getMonth()+1
consloe.log(month)	//如果不加1的话会是上一个月份,因为是从0到11,所以要加1
//获取日期
var d = date.getDate()
console.log(d)	//获取到当前的日期	19
//获取星期
var day = date.getDay()
console.log(day)	//获取当前的星期		3
//-------------------------------------------------------------------------
//获取时
var hour = date.getHours()
console.log(hour)	//获取当前的时	22
//获取分
var minute = date.getMinutes()
console.log(miunte)		//获取当前的分钟		30
//获取秒
var second = date.getSeconds
console.log(second)		//获取当前的秒	10
//获取时间戳
var time = dete.getTime()
console.log(time)		//获取时间戳		1666189599990
	
//小案例	3天前是星期几
var date = new Date()
	var time = date.getTime() 	//获取当前的时间戳
	//3天前	从当前的时间戳-3天的时间戳
	time -= 3*24*3600*1000	//3天前的时间戳
	//通过时间戳设置时间日期对象
	var date1 = new Date(time)
	consloe.log(date1)		//Sun Oct 16 2022 22:30:20 GMT+0800 (中国标准时间)

设置具体的日期
通过时间日期对象,可以改变其中具体的年月日时分秒

var date = new Date()
console.log(date)	//当前日期	Wed Oct 19 2022 22:41:47 GMT+0800 (中国标准时间)
//设置年份
date.setFullYear(2000)
console.log(date)	//Tue Oct 19 2000 22:36:56 GMT+0800 (中国标准时间)
//设置月份
date.setMonth(4)	//实际年份减 1
console.log(date)	
//设置日期
date.setDate(10)
console.log(date)	//Mon Oct 10 2022 22:39:40 GMT+0800 (中国标准时间)
//设置时
date.setHours(20)
console.log(date)	//Mon Oct 10 2022 20:39:40 GMT+0800 (中国标准时间)
//设置分
date.steMinutes(20)
console.log(date)	//Mon Oct 10 2022 20:20:40 GMT+0800 (中国标准时间)
//设置秒
date.steSeconds(20)
console.log(date)	//Mon Oct 10 2022 20:20:20 GMT+0800 (中国标准时间)
//通过设置时间戳来设置整个时间日期对象
date.strTime(0)
console.log(date)	//Thu Jan 01 1970 08:00:00 GMT+0800 (中国标准时间)

时间日期格式化

var date =new Date()
console.log(date)	//Wed Oct 19 2022 22:48:25 GMT+0800 (中国标准时间)
//转换成更好识别的结果
console.log(date.toLocealeString())		//2022/10/19 22:48:25
//只格式化日期
console.log(date.toLocaleDateString())	//2022/10/19
//只格式化分秒
console.log(date.toLocaleTimeString())	//22:48:25

总结
获取具体时间
date.getFullYear() 获取到当前的年

date.getMonth() 获取到当前的月份

date.getDate() 获取当前的日期

date.getDay() 获取当星期

date.getHours() 获取时

date.getMinutes() 获取分

date.getSeconds() 获取秒

date.getTime() 获取时间戳

设置具体的时间
daet.setFullYear() 设置年份

date.setMonth() 设置月

date.setDate() 设置日期

date.setHours() 设置时

date.Minutes()设置分

date.Seconds()设置秒

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值