javascript實用Date工具

 

時間字符串和年月日數據之間的自由轉換工具:2018年更新版工具

上代碼:code

/**
 * @Desc:   時間處理工具
 * @Author: 拿飯盒當菸灰缸
 * @Date:   2018-02-27 15:42:44
 * @Last Modified time: 2018-02-28 15:21:33
 */

/**
 * 根據時間格式,將數字格式的時間轉換爲格式字符串
 * @param  {[type]} secondtime   [description]
 * @param  {[type]} formatString [description]
 * @return {[type]}              [description]
 */
const formatTime = (secondtime, formatString) => {
  formatString = formatString || 'DD days hh:mm:ss S'
  if (/SS+/.test(formatString)) {
    console.error('formatTime', '毫秒格式錯誤,不能有多個連續的S出現')
    return
  }

  let timeKey = [{
    name: 'day',
    regString: 'D+'
  }, {
    name: 'hour',
    regString: 'h+'
  }, {
    name: 'minute',
    regString: 'm+'
  }, {
    name: 'second',
    regString: 's+'
  }]

  if (!/S/.test(formatString)) {
    secondtime = Math.round(secondtime)
  }

  let timeNumbers = getTimeNumbers(secondtime)

  for (let i = 0, len = timeKey.length; i < len; i++) {
    formatString = formatString.replace(new RegExp(timeKey[i].regString), function (matchString, index, originalString) {
      return formatNumber(timeNumbers[timeKey[i].name], matchString.length)
    })
  }

  // 毫秒只支持3位模式
  formatString = formatString.replace(/S/, formatNumber(timeNumbers.milli, 3))
  return formatString
}

/**
 * 根據時間number獲取小時,分鐘,秒,毫秒數
 * @param  {[type]} secondtime [description]
 * @return {[type]}            [description]
 */
const getTimeNumbers = (secondtime) => {
  // 轉成字符串
  secondtime = secondtime.toFixed(3)
  // 從小數點切分
  let timeArray = secondtime.split('.')
  // 小數點後三位是毫秒部分
  let milliSecond = 0
  if (timeArray[1]) {
    milliSecond = Math.round(Number('0.' + timeArray[1]) * 1000)
  }
  // 分別獲取時分秒
  let day = 0
  let hour = 0
  let minute = 0
  let second = 0
  // 一共多少秒
  let totalSeconds = Number(timeArray[0])
  // 幾天
  day = Math.floor(totalSeconds / 3600 / 24)
  // 剩餘秒數
  let dayRemain = totalSeconds % (3600 * 24)
  // 幾個小時
  hour = Math.floor(dayRemain / 3600)
  // 剩餘秒數
  let hourRemain = dayRemain % 3600
  // 幾分鐘
  minute = Math.floor(hourRemain / 60)
  // 剩餘秒數
  second = hourRemain % 60

  let timeNumbers = {
    day: day,
    hour: hour,
    minute: minute,
    second: second,
    milli: milliSecond
  }

  return timeNumbers
}

/**
 * 數字格式化,在數字前邊加0,補全到幾位,好比輸入1,3,則輸出001
 * @param  {[type]} number [description]
 * @param  {[type]} n      [description]
 * @return {[type]}        [description]
 */
const formatNumber = (number, n) => {
  n = n || 2
  number = number + ''
  let numberArray = number.split('')
  if (numberArray.length < n) {
    let len = n - numberArray.length
    for (let i = 0; i < len; i++) {
      numberArray.unshift('0')
    }
  }
  let res = numberArray.join('')
  return res
}

export {
  formatTime,
  getTimeNumbers,
  formatNumber
}
相關文章
相關標籤/搜索