常用时间方法汇总

先了解Date对象一些原生方法

var oDate = new Date()
  //获取Date对象的某值
  console.log(oDate.getFullYear());       //年(以四位数字返回年份)
  console.log(oDate.getMonth()+1);        //月(0 ~ 11)
  console.log(oDate.getDate());           //日(1 ~ 31)
  console.log(oDate.getHours());          //时(0 ~ 23)
  console.log(oDate.getMinutes());        //分(0 ~ 59)
  console.log(oDate.getSeconds());        //秒(0 ~ 59)
  console.log(oDate.getMilliseconds());   //毫秒值(0 ~ 999)
  console.log(oDate.getDay());            //周几(0 ~ 6)
  console.log(oDate.toDateString());            //将Date对象的日期部分转成字符串(通常用来对比时间是否相同)
  console.log(oDate.toTimeString());            //将Date对象的时间部分转成字符串

  //设置Date对象的某值
  oDate.setDate()         // 月的某一天 (1 ~ 31)。
  oDate.setMonth()        // 月份 (0 ~ 11)。
  oDate.setFullYear()     // 年(四位数字)。
  oDate.setHours()        // 时 (0 ~ 23)。
  oDate.setMinutes()      // 分 (0 ~ 59)。
  oDate.setSeconds()      // 秒 (0 ~ 59)。
  oDate.setMilliseconds() // 毫秒值 (0 ~ 999)。
  • Date对象与时间戳相互转换(3种方法)
    // Date获取时间戳
      Date.parse(new Date()); //只能精确到秒
      oDate.getTime();
      oDate.valueOf();
    // 时间戳转Date对象
      oDate.setTime() 

时间格式化常用方法

  • 时间戳转固定时间格式
/**
 * 最常用
 * 时间戳 => 2017-12-05 15:55:32
 */
  function formatTime(s){
    var fix = function(num){
      return ('' + num).length < 2 ? ((new Array(3)).join('0') + num).slice(-2) : '' + num;
    }
    var time = new Date(s);
    return time.getFullYear()+"-"+fix(time.getMonth()+1)+"-"+fix(time.getDate())+" "+fix(time.getHours())+":"+fix(time.getMinutes())+":"+fix(time.getSeconds());
  }

/**
 * 今天星期['日','一','二','三','四','五','六']
 */
  function severalWeek(){
    var arr = ['日','一','二','三','四','五','六'];
    var severalWeek = new Date();
    return arr[severalWeek.getDay()];
  }

/**
 * 时间戳 => 2017.12.26 星期二 09:44
 */
  function formatTime(s){
    var fix = function(num){
      return ('' + num).length < 2 ? ((new Array(3)).join('0') + num).slice(-2) : '' + num;
    }
    var time = new Date(s);

    var arr = ['日','一','二','三','四','五','六'];
    day = arr[time.getDay()];

    return time.getFullYear()+"."+fix(time.getMonth()+1)+"."+fix(time.getDate())+" 星期"+day+" "+fix(time.getHours())+":"+fix(time.getMinutes());
  }

/**
 * 时间戳 => ['今天','昨天','周x']
 */
  function orderTime(str){
    var d = new Date(str);
    var todaysDate = new Date();
    var yestdayDate = new Date(new Date()-24*3600*1000);
    if(d.toDateString() == todaysDate.toDateString()){
      return "今天"
    }else if(d.toDateString() == yestdayDate.toDateString()){
      return "昨天"
    }else{
      var arr = ['周日','周一','周二','周三','周四','周五','周六'];
      var week = new Date(str);
      return arr[week.getDay()];
    }
  }

/**
 * 时间戳 => ['刚刚','x分钟前','x小时前','x天前','x个月前','x年前']
 */
  function formatPassTime(startTime) {
    var currentTime = Date.parse(new Date()),
      time = currentTime - startTime,
      day = parseInt(time / (1000 * 60 * 60 * 24))
      hour = parseInt(time / (1000 * 60 * 60))
      min = parseInt(time / (1000 * 60))
      month = parseInt(day / 30)
      year = parseInt(month / 12)
    if (year) return year + "年前"
    if (month) return month + "个月前"
    if (day) return day + "天前"
    if (hour) return hour + "小时前"
    if (min) return min + "分钟前"
    else return '刚刚'
  }

/**
 * 时间戳 => ['今天','昨天','mm:ss','MM-DD']
 */
  function orderTime(str){
    var fix = function(num){
      return ('' + num).length < 2 ? ((new Array(3)).join('0') + num).slice(-2) : '' + num;
    }
    var d = new Date(str);
    var todaysDate = new Date();
    var yestdayDate = new Date(new Date()-24*3600*1000);
    if(d.toDateString() == todaysDate.toDateString()){
      return fix(d.getHours())+":"+fix(d.getMinutes())
    }else if(d.toDateString() == yestdayDate.toDateString()){
      return fix(d.getHours())+":"+fix(d.getMinutes())
    }else{
      return fix(d.getMonth()+1)+"-"+fix(d.getDate())
    }
  }
  • 距离截止日期还有x天 x小时 x分钟 x秒

    /**
    * 距离截止日期还有x天 hh:mm:ss (自动更新)
    * 截止日期endTime(时间戳) => 倒计时剩余:n天 hh:mm:ss
    */
    function showRemainTime(endTime) {
      var fix = function(num){
        return ('' + num).length < 2 ? ((new Array(3)).join('0') + num).slice(-2) : '' + num;
      }
      var nowtime = new Date();
      var endtime = new Date(endTime);//截止时间
      var timeLag = Math.floor((endtime.getTime() - nowtime.getTime()) / 1000);
      var d = Math.floor(timeLag / (24 * 60 * 60));
      var h = Math.floor(timeLag / (60 * 60) % 24);
      var m = Math.floor(timeLag / 60 % 60);
      var s = Math.floor(timeLag % 60);
      h = fix(h);
      m = fix(m);
      s = fix(s);
      console.log("倒计时剩余" + d + "天 " + h + ":" + m + ":" + s);
      if(timeLag<=0){
        console.log("活动已结束");
        return;
      }
      setTimeout(showRemainTime,1000,endTime);//1秒后获取当前时间,计算并更新剩余多少时间
    }
  • 判断是不是某一天

    /**
    * n天(前|后)的时间
    * 时间戳 => n天(前|后)的时间戳
    */
    var newTime = new Date()-24*3600*1000;   // 昨天
    var newTime = new Date()-24*3600*1000*2; // 前天
    var newTime = new Date()-24*3600*1000*3; // 3天前
    
    var newTime = new Date().getTime()+24*3600*1000;   // 明天
    var newTime = new Date().getTime()+24*3600*1000*2; // 后天
    var newTime = new Date().getTime()+24*3600*1000*3; // 3天后
    

/**

  • 是不是今天
  • 时间戳 => (是|不是)
  • /
    function isToday(str){
    var d = new Date(str);
    var todaysDate = new Date();
    if(d.toDateString() == todaysDate.toDateString()){ //将需要检测的时间和当前时间的时,分,秒,毫秒分别设置为0,然后对比年月日是否相同
    return true;                                            
    } else {
    return false;                                           
    }
    }

/**

  • 是不是昨天
  • ‘2016-06-06 06:06:06’ => (是|不是)
  • /
    function isYestday(str){
    var d = new Date(str);
    var yestdayDate = new Date(new Date()-2436001000);
    if(d.toDateString() == yestdayDate.toDateString()){
    return true;                                            
    } else {
    return false;                                           
    }
    }
  • 时间排序
    /**
    * 时间排序(数组)
    * in: ['2018-03-05', '2013-06-12','2019-03-12','2018-03-05','2014-02-22']
    * out:["2013-06-12", "2014-02-22", "2018-03-05", "2018-03-05", "2019-03-12"]
    */
    var arr = ['2018-03-05', '2013-06-12','2019-03-12','2018-03-05','2014-02-22'];
    arr.sort(function(a,b){return new Date(a)-new Date(b)});
    console.log(arr);//["2013-06-12", "2014-02-22", "2018-03-05", "2018-03-05", "2019-03-12"]

    iOS端不支持”2018-08-08 11:11:11”
    需要转换为”2018/08/08 11:11:11”
    var d = new Date(str.replace(/-/g,"/"));