javascript实用Date工具

 

时间字符串和年月日数据之间的自由转换工具:2018年更新版

上代码:

/**
 * @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
}

 

 

 

 

 

posted @ 2016-07-04 16:02  拿饭盒当烟灰缸  阅读(172)  评论(0编辑  收藏  举报