JS日期对象

日期对象

使用new进行实例化

  • 获得当前时间
    //1.得到当前时间
    const time =new Date();
    console.log(time);
    //2.得到指定时间
    const date1 = new Date('2023-5-11');
    console.log(date1);
    
  • 案例:将当前时间展示在屏幕上
      <style>
          div{
              width: 300px;
              height: 40px;
              border: 1px solid #ccc;
              text-align: center;
              line-height: 40px;
          }
      </style>
      <div></div>
      <script>
          const div=document.querySelector("div");
          function getMyDate() {
              const date =new Date();
              console.log(date);
    
              let y=date.getFullYear();
              console.log(y);
              let m=date.getMonth()+1;
              let s=date.getDate();
              let h=date.getHours();
              let min=date.getMinutes();
              let sec=date.getSeconds();
              h=h<10?'0'+h:h
              s=s<10?'0'+s:s
              min=min<10?'0'+min:min
              sec=sec<10?'0'+sec:sec
              return `今天是${y}-${m}-${s} ${h}:${min}:${sec}`
          }
          
          div.innerHTML=getMyDate();//页面刷新一开始显示
          setInterval(function(){
              div.innerHTML=getMyDate();
          },1000)
      </script>
    
  • 或者采用内置函数
    div.innerHTML=date.toLocaleString();
    
  • 时间戳
    • 时间戳是指1970年1月1日00时00分00秒起至今的毫秒数
    • 将来的时间戳-现在的时间戳=剩余的时间毫秒数
    • 三种方法获取时间戳
        //1.getTime()
          const date =new Date();
          console.log(date.getTime());
          //2.+new Date()
          console.log(new Date());
          console.log(+new Date());//把字符串转化为字符型
          //3.Date.now(),只能得到当前的时间戳,其他都能得到指定时间的
          console.log(Date.now());
      
  • 5
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值