javascript 時間轉換整理

  /**
   * 生成具體日期時間
   * @param timestamp 時間戳
   * @type yyyy-mm-dd hh:mm:ss
   */
  createTime(timestamp){ 
    var date = timestamp ? new Date(timestamp) : new Date();//實例一個時間對象,timestamp無則是當前時間;
    var year = date.getFullYear();//獲取系統的年;
    var month = date.getMonth() + 1;//獲取系統月份,由於月份是從0開始計算,所以要加1
    var day = date.getDate(); //獲取系統日
    var hour = date.getHours();//獲取系統時間
    var minute = date.getMinutes(); //分
    var second = date.getSeconds();//秒
    return year + '-' + this.formateDateDounle(month) + '-' + this.formateDateDounle(day) + ' ' + this.formateDateDounle(hour) + ':' + this.formateDateDounle(minute) + ':' + this.formateDateDounle(second)
  },
  /**
   * 獲取日期(年月日)
   * @param dateDesc
   * @type yyyy-mm-dd
   */
  getDay(timestamp){
    var date = timestamp ? new Date(timestamp) : new Date()
    var year = date.getFullYear();//獲取系統的年;
    var month = date.getMonth() + 1;//獲取系統月份,由於月份是從0開始計算,所以要加1
    var day = date.getDate(); //獲取系統日
    return year + '-' + this.formateDateDounle(month) + '-' + this.formateDateDounle(day)
  },
  /**
   * 獲取後幾個小時時間
   * @param num 後幾小時
   * @param timestamp 時間戳
   * @type yyyy-mm-dd hh:mm:ss
   */
  getLateTime(num, timestamp){
    if (!timestamp) { //不傳則爲當前時間延遲
      timestamp = new Date().getTime()
    }
    return this.createTime(timestamp + num * 60 * 60 * 1000)
  },
  /**
   * 時間轉換兩位數字
   * @param num
   */
  formateDateDounle(num){
    return num.toString().length > 1 ? num : '0' + num
  },
  /**
   * 獲取時分
   * @param date 格式 yyyy-mm-dd hh:mm:ss
   * @type hh:mm
   */
  getHourMin(date){
    let dateArr = this.getLateTime(1).split(' ')[1].split(':')
    return dateArr[0] + ':' + dateArr[1];
  }

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章