它是一个构造函数,要用new来创建
1.获取当前年月日,周,时分秒。在获取月份的时候+1,月份从0开始计算;
星期是:周一1,周六6,周天0
var date = new Date();
console.log(date);
console.log(date.getFullYear());
console.log(date.getMonth() + 1);//在获取月份的时候+1,月份从0开始计算
console.log(date.getDate());
console.log(date.getDay());//周一1,周六6,周天0
console.log(date.getHours());
console.log(date);
console.log(date.getSeconds());
结果为
2. 如果需要返回格式为00:00:00
用三元运算表达式子
function getTime() {
var time = new Date();
var h = time.getHours();
h = h < 10 ? '0' + h : h;
var min = time.getMinutes();
min = min < 10 ? '0' + min : min;
var second = time.getSeconds();
second = second < 10 ? '0' + second : second;
return h + ':' + min + ':' + second;
}
console.log(getTime());
3.
var date1 = new Date(2002, 11, 4);//输出是12月,相当于下标为11
console.log(date1);
var date2 = new Date('2002-11-4');//11月
console.log(date2);
4.获得总毫秒数(时间戳),距离1970年1月1号过的毫秒数
var date = new Date();
console.log(date.valueOf());
console.log(date.getTime());
上面可简写,有下面两种方式:
// 简写1
var date1 = +new Date();
console.log(date1);
//简写2
console.log(Date.now()); */
5.京东倒计时案例
仔细体会该计算
function countDown(time) {
var nowTime = +new Date();//返回当前时间的总毫秒数
var inputTime = +new Date(time);//返回用户输入时间的毫秒数
var times = (inputTime - nowTime) / 1000;//时间差毫秒转成秒
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;
return '距离下课还有:\n' + d + '天' + h + '时' + m + '分' + s + '秒';
}
console.log(countDown('2024-6-4 13:00:00'));