一.创建日期对象
1.new Date():获得当前的时间
2.new Date(datestring):用指定的日期和时间创建对象
3.new Date(millisecond):用指定的毫秒值创建对象,millisecond为0时对应1970年1月1日
4.new Date(year,month,day,hours,minutes,second,millisecond):
用于指定日期创建日期对象,7个数字代表年,月,日,时,分,秒,毫秒
<script type="text/javascript">
// 1.获得当前时间
var now = new Date()
console.log(now);
console.log(now.toString());
console.log(now.toLocaleDateString()); // 2021/9/8
console.log(now.toLocaleTimeString()); // 下午8:18:05
//2.创建指定日期和时间
var time = new Date('2012/12/12');
console.log(time); //Wed Dec 12 2012 00:00:00 GMT+0800 (中国标准时间)
console.log(time.toString()); //Wed Dec 12 2012 00:00:00 GMT+0800 (中国标准时间)
//3.用指定的毫秒值创建对象
var millisecond = new Date(0)
console.log(millisecond); // 默认:Thu Jan 01 1970 08:00:00 GMT+0800 (中国标准时间)
var did = new Date(1631104059111) //Wed Sep 08 2021 20:27:39 GMT+0800 (中国标准时间)
console.log(did)
//4.指定日期和时间创建对象
var times= new Date(2021,8,8,20,28,12,14) //Wed Sep 08 2021 20:28:12 GMT+0800 (中国标准时间)
console.log(times);
//注意:javascript 从0开始计算月份,到11,所以上述例子,8代表9月
</script>
二.日期的获取方法
方法 | 描述 |
getTime() 或 valueOf() | 返回1970 年 1 月 1 日至今的 毫秒数 |
getFullYear() | 获取四位的年(yyyy) |
getMonth() | 获取月(0-11) |
getDate() | 以数值返回一个月中的某一天(1-31 |
getDay() | 以数值返回一周中的某一天(0-6) |
getHours() | 获取小时(0-23) |
getMinutes() | 获取分(0-59) |
getSeconds() | 获取秒(0-59) |
getMilliseconds() | 获取毫秒(0-999) |
三.日期的设置
方法 | 描述 |
setTime() | 以毫秒设置时间,返回设置的毫秒值 |
setFullYear() | 设置年(可选月和日) |
setMonth() | 设置月(0-11) |
setDate() | 以数值设置月的某一天 (1 ~ 31) |
setHours() | 设置小时(0-23) |
setMinutes() | 设置分(0-59) |
setSeconds() | 设置秒(0-59) |
setMilliseconds() | 设置毫秒(0-999) |
四.案例:求我距离下个生日的的时间(2022年1月2日,00:00)
<script type="text/javascript">
// 1.获得当前时间的毫秒值
var now = new Date().getTime();
//2.获得下次生日的毫秒值
var time = new Date(2022, 1, 2, 0, 0, 0).getTime();
//3.求差得到剩多少秒
var count = (time - now) / 1000;
//4.得出结论
var d = parseInt(count / 60 / 60 / 24); //得到天数
var h = parseInt(count / 60 / 60 % 24); //得到小时
var m = parseInt(count / 60 % 60 ); //得到分钟
var s = parseInt(count % 60 ); //得到秒
console.log('距离我的生日还差' + d + '天' + h + '小时' + m + '分钟' + s + '秒');
</script>