2:Date构造函数

2)使用Date

//1 没有参数
var date = new Date();
console.log(date); //Tue Feb 16 2021 21:31:43 GMT+0800 (中国标准时间)

//2 数值参数
var date1 = new Date(2019,10,1);
console.log(date1); //Fri Nov 01 2019 00:00:00 GMT+0800 (中国标准时间)
//返回的是十一月  返回的比我写的 大一个月

//3 字符串参数 [ 最常用 ]
var date2 = new Date('2019-10-1 10:15:02');
console.log(date2); //Tue Oct 01 2019 00:00:00 GMT+0800 (中国标准时间)

 3)格式化日期

var date = new Date();//实例化一个日期对象
console.log(date.getFullYear()); //
console.log(date.getMonth() + 1); //[返回的月份 比实际小一个月 需要+1]
console.log(date.getDay()); //周几 [ 周日是0 ]
console.log(date.getDate());//返回几号
console.log(date.getHours());//
console.log(date.getMinutes());//
console.log(date.getSeconds());//
 

4)小demo:格式化日期

var date = new Date();//实例化一个日期对象

// 我们写一个 2019年 5月 1日 星期三
var year = date.getFullYear();
var month = date.getMonth()+1;
var dates = date.getDate();
var day = date.getDay();
var arr = ['星期日','星期一','星期二','星期三','星期四','星期五','星期六'];
console.log('今天是:' + year + '年\40' + month + '月\40' + dates + '日\40' + arr[day]);
//执行结果: 今天是:2021年 2月 17日 星期三

5)小demo:格式化时分秒

// 要求封装一个函数返回当前的时分秒 格式 08:08:08
function getTime() {
    var date = new Date();//实例化一个日期对象
    var h = date.getHours();
    h = h < 10 ? '0' + h : h;
    var m = date.getMinutes();
    m = m < 10 ? '0' + m : m;
    var s = date.getSeconds();
    s = s < 10 ? '0' + s : s; //三元表达式 小于10就给加个0
    return h + ':' + m + ':' + s;
    
}
alert(getTime()); //09:04:56

6)时间戳

//1 获取的是 当前时间距离1970.1.1总的毫秒数
var date = new Date();//实例化一个日期对象
console.log(date.valueOf());//方法1
console.log(date.getTime());//方法2
var date1 = +new Date();//方法3 [ 最常用 ]
console.log(date1);
console.log(Date.now());//方法4 [ H5新增 有兼容性问题]

7)倒计时demo

//1 核心算法:活动开始的时间 - 现在的时间 = 剩余时间
//2 但是不能拿时分秒直接相减 比如10分减25分 结果是负数
//3 我们用时间戳来计算 用户输入的毫秒数 - 现在的毫秒数 = 剩余的毫秒数
//4 把剩余的时间戳转 天 时 分 秒
-------------------转换公式-------------------------
1秒 = 1000毫秒
//  d = parseInt(总秒数/ 60/60 /24); //  计算天数
//  h = parseInt(总秒数/ 60/60 %24); //   计算小时
//  m = parseInt(总秒数 /60 %60 ); //   计算分数
//  s = parseInt(总秒数%60); //   计算当前秒数
--------------------------------------------
function countDown(time) {
    var nowTime = +new Date();//获取当前时间戳
    var inputTime = +new Date(time); //获取客户输入时间的时间戳
    var times = 0;//时间差变量
    //判断客户输入时间是否小于当前时间
    if (inputTime > nowTime) {
        times = (inputTime - nowTime) / 1000; //把毫秒换算成秒 再计算
    } else {
        alert('输入的时间小于当前时间');
    }
    //转换天 时 分 秒
    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 d + '' + h + '小时' + m + '' + s + '';
}
console.log(countDown('2021-3-7'));
执行结果:17天13小时04分29秒

 

posted @ 2021-02-16 22:17  棉花糖88  阅读(139)  评论(0编辑  收藏  举报