日期的部分处理

210 阅读1分钟

日期的部分常用处理

   // 转化成2017-01-02
  toDate(date) {
      const nowDate = date;
      const y = nowDate.getFullYear();
      let m = nowDate.getMonth() + 1;
      m = m < 10 ? `0${m}` : m;
      let d = nowDate.getDate();
      d = d < 10 ? `0${d}` : d;
      return `${y}-${m}-${d}`;
  },
  // 转化成2018-11-01 00:00;00
  toDateTime(date) {
      const nowDate = date;
      const y = nowDate.getFullYear();
      let m = nowDate.getMonth() + 1;
      m = m < 10 ? `0${m}` : m;
      let d = nowDate.getDate();
      d = d < 10 ? `0${d}` : d;
      let h = nowDate.getHours();
      h = h < 10 ? `0${h}` : h;
      let min = nowDate.getMinutes();
      min = min < 10 ? `0${min}` : min;
      const s = nowDate.getSeconds();
      return `${y}-${m}-${d} ${h}:${min}:${s}`;
  },
  // 获取当前月第一天
  toDatafirstdate(){
      var myDate = new Date();
      var thisyear = myDate.getFullYear();
      var thismonth = myDate.getMonth();
      if(thismonth==0){  
        thismonth=12;  
        thisyear=thisyear-1;  
      }  
      if (thismonth < 9) {  
        thismonth = "0" + (thismonth+1);  
      }  
      return  thisyear + "-" + thismonth + "-" + "01";
  },
  // 获取上月第一天
  toDatalastdate(){
    var myDate = new Date();
    var thisyear = myDate.getFullYear();
    var thismonth = myDate.getMonth();
    if(thismonth==0){  
      thismonth=12;  
      thisyear=thisyear-1;  
    }  
    if (thismonth < 9) {  
      thismonth = "0" + thismonth;  
    }  
    return  thisyear + "-" + thismonth + "-" + "01";
  },
  // 获取上月最后一天
  togetlastdate(){
      var nowdays = new Date();  
      var year = nowdays.getFullYear();  
      var month = nowdays.getMonth();  
      if(month==0){  
        month=12;  
        year=year-1;  
      }  
      if (month < 10){  
        month = "0" + month;  
      }  
      var myDate = new Date(year, month, 0);  
      var lastDay = year + "-" + month + "-" + myDate.getDate();
      return lastDay;
  }
  // 时间转换格式 适配于安卓系统下input date默认值的显示
   function datestr(x,y) { 
        var z = {M:x.getMonth()+1,d:x.getDate(),h:x.getHours(),m:x.getMinutes(),s:x.getSeconds()}; 
        y = y.replace(/(M+|d+|h+|m+|s+)/g,function(v) {return ((v.length>1?"0":"")+eval('z.'+v.slice(-1))).slice(-2)}); 
        return y.replace(/(y+)/g,function(v) {return x.getFullYear().toString().slice(-v.length)}); 
    }
    console.log(datestr(new Date(),"yyyy-MM-dd"))
    console.log(datestr(new Date(),"yyyy-MM-dd hh-mm-ss"))
    
// 时间转换格式 适配于ios系统下input date默认值的显示
gettme(){
        let currentDate = new Date().toLocaleDateString();
        let temp = currentDate.split("/");
        this.start_time = `${temp[0]}-${temp[1] <= 9
          ? "0" + temp[1]
          : temp[1]}-${temp[2] <= 9 ? "0" + temp[2] : temp[2]}`;
          
        this.end_time = `${temp[0]}-${temp[1] <= 9
          ? "0" + temp[1]
          : temp[1]}-${temp[2] <= 9 ? "0" + temp[2] : temp[2]}`;
      },