Javascript-内置对象Date

它是一个构造函数,要用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'));

  • 8
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值