JavaScript中的时间日期处理

时间日期对象创建

当前时间的时间日期对象

var date = new Date()
console.log(date) // Wed Oct 26 2022 16:33:43 GMT+0800 (中国标准时间)

创建好的是一个对象,但是当输出的时候被浏览器自动转为字符串输出了。获取到的是当前本地的时间日期对象。如果把本地的时间日期改掉,获取到的时间日期对象会随着本地时间变化。

指定的时间日期对象

1.字符串形式参数

var date = new Date('2022-10-01 00:00:00') // 字符串格式固定的:年-月-日 时:分:秒
console.log(date);//Sat Oct 01 2022 00:00:00 GMT+0800 (中国标准时间)

 2.多个数字 - 当使用多个数字传递参数,表示月份的时候,时间日期中使用0~11这12个数字来描述1~12月的

 var date = new Date(2022, 9, 01, 0, 0, 0); // 想表示的月份,数字要比实际的月份-1
 console.log(date);//Sat Oct 01 2022 00:00:00 GMT+0800 (中国标准时间)

 3.传入一个时间戳数字 - 时间戳:从1970年1月1日0点0分0秒到现在走过的所有毫秒数 - 毫秒比秒更小的一个单位 - 1秒=1000毫秒

var date = new Date(0); // 1970-1-1 0:0:0 到目前走过的毫秒数为0
console.log(date); //Thu Jan 01 1970 08:00:00 GMT+0800 (中国标准时间)

注:中国标准时间,叫东八区,+8时区,是世界标准时间+8个小时

获取具体的时间日期

// 通过时间日期对象可以从中获取到更加具体的时间日期
var date = new Date()
 // 获取到年
var year = date.getFullYear()
console.log(year);
 // 获取月份 - 获取到时间日期对象中的月份 - 这里的月份是通过0~11来描述1~12月的
 var month = date.getMonth() + 1
console.log(month);
 // 获取日期
var d = date.getDate()
console.log(d);
 // 获取星期
var day = date.getDay()
console.log(day);
 // 获取时
var hour = date.getHours()
console.log(hour);
 // 获取分
var minute = date.getMinutes()
console.log(minute);
 // 获取秒
var second = date.getSeconds()
console.log(second);
 // 获取时间戳
var time = date.getTime()
console.log(time);

注:时间戳,指的是,格林尼治时间1970年1月1日0点0分0秒到现在走过的毫秒数。利用时间戳可以方便计算时间,例如:计算100天以前是几月几号

设置时间日期

通过时间日期对象,可以将其中的年月日时分秒进行设置,改变时间日期对象的时间。

var date = new Date()
 // 设置为年份
date.setFullYear(年份)
console.log(date);
 // 设置月份
date.setMonth(当前月份-1) // 设置时间日期对象中的月份 - 这里的月份是通过0~11来描述1~12月的
console.log(date);
 // 设置日期
date.setDate(日)
console.log(date);
 // 设置时
date.setHours(时)
console.log(date);

 // 设置分
date.setMinutes(分)
console.log(date);

 // 设置秒
date.setSeconds(毫秒)
console.log(date);

 //  设置时间日期对象对应的时间戳 - 直接用时间戳就能将时间日期对象中的年月日时分秒全部改变
date.setTime(时间戳)
console.log(date);

日期格式化

var date = new Date();
console.log(date);//Wed Oct 26 2022 16:56:28 GMT+0800 (中国标准时间)

// 转换成更好识别的结果 - date.toLocaleString()
console.log(date.toLocaleString()); //2022/10/26 16:56:28

// 光格式化日期 - date.toLocaleDateString()
console.log(date.toLocaleDateString()); //2022/10/26

// 格式化时分秒 - date.toLocaleTimeString()
console.log(date.toLocaleTimeString()); //16:56:28

时间戳的获取

获取时间戳 - 通过时间戳,可以实现时间日期之间的加减乘除运算,以便获取到目标时间

// 1.
var date = +new Date();
console.log(date);

// 2.
对象.getTime()

//3.
Date.parse("年-月-日 时:分:秒");
console.log(Date.parse("2022-10-1 0:0:0"));

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值