手写JS之计算两种不同时间格式的差值

现有需求:给定一个视频的开始时间点和持续时间段,判断当前时间看该视频应该是回放?是预告?还是正在播放?

思路:把所能得到的时间都转换为时间戳进行比较。

知识点:

  1. 获取当前时间的时间戳

    //第一种方法:
    var timestamp1 = Date.parse(new Date());
    //第二种方法:
    var timestamp2 = new Date().valueOf();
    //第三种方法:
    var timestamp3 = new Date().getTime();
    
  2. 日期字符串转时间戳

    var date = '2015-03-05 17:59:00.0';
    date = date.substring(0,19);    
    date = date.replace(/-/g,'/'); //必须把日期'-'转为'/'
    var timestamp = new Date(date).getTime();
    
  3. 时间段转时间戳

    9mins:  9*60*1000
    

拓展知识点:

  1. 时间戳转日期字符串

    var timestamp = '1425553097';
    var d = new Date(timestamp * 1000);    //根据时间戳生成的时间对象
    var date = (d.getFullYear()) + "-" + 
               (d.getMonth() + 1) + "-" +
               (d.getDate()) + " " + 
               (d.getHours()) + ":" + 
               (d.getMinutes()) + ":" + 
               (d.getSeconds());
    
  2. 当前时间转日期字符串

    var now = new Date();
    var yy = now.getFullYear();      //年
    var mm = now.getMonth() + 1;     //月
    var dd = now.getDate();          //日
    var hh = now.getHours();         //时
    var ii = now.getMinutes();       //分
    var ss = now.getSeconds();       //秒
    var clock = yy + "-";
    if(mm < 10) clock += "0";
    clock += mm + "-";
    if(dd < 10) clock += "0";
    clock += dd + " ";
    if(hh < 10) clock += "0";
    clock += hh + ":";
    if (ii < 10) clock += '0'; 
    clock += ii + ":";
    if (ss < 10) clock += '0'; 
    clock += ss;
    document.write(clock);     //获取当前日期
    
posted @ 2021-08-22 22:19  似漆  阅读(68)  评论(0编辑  收藏  举报