image.png

获取时 分 秒 的封装

  1. var date=new Date();
  2. var h=date.getHours();
  3. var f=date.getMinutes();
  4. var m=date.getSeconds();
  5. var sum=hNum(h)+":"+hNum(f)+":"+hNum(m);
  6. console.log(sum);
  7. function hNum(num){
  8. if(num<10){
  9. num="0"+num;
  10. }
  11. return num;
  12. }

倒计时

  1. <div id="app"></div>
  2. <script>
  3. setInterval(go,1000);
  4. function go(){
  5. var app =document.querySelector("#app")
  6. var date=new Date();
  7. var h=date.getHours();
  8. var f=date.getMinutes();
  9. var m=date.getSeconds();
  10. var sum=hNum(h)+":"+hNum(f)+":"+hNum(m);
  11. app.innerHTML=sum
  12. console.log(sum);
  13. }
  14. function hNum(num){
  15. if(num<10){
  16. num="0"+num;
  17. }
  18. return num;
  19. }

解析字符串获取距离时间戳

  1. var s="2021:10:13,18:00:00";
  2. // var arr=s.replace(","," ");
  3. // console.log(arr.slice(","));
  4. s=s.split(",");
  5. var arr=[];
  6. var reg=/\:/g;
  7. arr[0]= s[0].replace(reg,"-");
  8. arr[1]=s[1];
  9. var list=arr.toString()
  10. list=list.replace(","," ");
  11. var startTime=(new Date()).getTime();
  12. var endTime=(new Date(list)).getTime();
  13. var gapTime=endTime-startTime;
  14. //获取多少秒
  15. var seconds=gapTime/1000;
  16. //获取小时
  17. var h=Math.floor(seconds/60/60);
  18. //获取相差秒数
  19. var mm=seconds-h*3600;
  20. //获取分钟数
  21. var f=Math.floor(mm/60);
  22. //获取秒数
  23. var m=Math.floor(mm-f*60);
  24. console.log(m);
  25. console.log(h);
  26. console.log(f);
  27. console.log("距离上晚自习还剩下"+h+"小时"+f+"分钟"+m+"秒");