日期时间相关代码片段

获取两个日期之间相差的天数

计算 Date 对象之间的差异(以天为单位)。

const getDaysDiffBetweenDates = (dateInitial, dateFinal) => (dateFinal - dateInitial) / (1000 * 3600 * 24);
getDaysDiffBetweenDates(new Date("2017-12-13"), new Date("2017-12-22")) // 9

格式化时间显示

完整版本

/**
 * 格式化时间显示
 * @param {Date} date 需要格式化的时间
 * @param {string} fmt 时间格式化字符串
 * @return {string} 格式化后的字符串
 */
function formatTime (date, fmt = 'YYYY-MM-DD HH:mm:ss') {
  date = typeof date === 'number' ? new Date(date) : date
  var o = {
    'M+': date.getMonth() + 1,
    'D+': date.getDate(),
    'h+': date.getHours() % 12 === 0 ? 12 : date.getHours() % 12,
    'H+': date.getHours(),
    'm+': date.getMinutes(),
    's+': date.getSeconds(),
    'q+': Math.floor((date.getMonth() + 3) / 3),
    'S': date.getMilliseconds()
  }
  var week = {
    '0': '\u65e5',
    '1': '\u4e00',
    '2': '\u4e8c',
    '3': '\u4e09',
    '4': '\u56db',
    '5': '\u4e94',
    '6': '\u516d'
  }
  if (/(Y+)/.test(fmt)) {
    fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length))
  }
  if (/(E+)/.test(fmt)) {
    fmt = fmt.replace(RegExp.$1, ((RegExp.$1.length > 1) ? (RegExp.$1.length > 2 ? '\u661f\u671f' : '\u5468') : '') + week[date.getDay() + ''])
  }
  for (var k in o) {
    if (new RegExp('(' + k + ')').test(fmt)) {
      fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? (o[k]) : (('00' + o[k]).substr(('' + o[k]).length)))
    }
  }
  return fmt
}
formatTime(new Date()) // "2018-01-30 11:13:27"
formatTime(new Date(), 'YYYY-MM-DD') // "2018-01-30"
formatTime(new Date(), 'HH:mm:ss') // "11:14:39"

简易版本

function formatTime (date, withTime = true) {
    const year = date.getFullYear()
    const month = date.getMonth() + 1
    const day = date.getDate()
    const hour = date.getHours()
    const minute = date.getMinutes()
    const second = date.getSeconds()
    const showDate = [year, month, day]
      .map(n => n.toString()[1] ? n : '0' + n).join('-')
    const showTime = [hour, minute, second]
      .map(n => n.toString()[1] ? n : '0' + n).join(':')
    return withTime ? showDate + ' ' + showTime : showDate
}

更简易版本

function formatTime (date, withTime = true) {
    const showDate = [date.getFullYear(), date.getMonth() + 1, date.getDate()]
      .map(n => n.toString()[1] ? n : '0' + n).join('-')
    const showTime = [date.getHours(), date.getMinutes(), date.getSeconds()]
      .map(n => n.toString()[1] ? n : '0' + n).join(':')
    return withTime ? showDate + ' ' + showTime : showDate
}

友好时间显示

/**
 * 获取友好的时间显示
 * @param {Date|number|string} time
 * > Date: 时间对象
 * > number: 时间戳
 * > string: 格式化的时间字符串,如'2017-10-01 18:00:00'
 * @param {boolean} 是否显示时间,默认false
 * @return {string} 友好的时间显示
 */
function friendlyTime (time, withTime = false) {
  let date = (time instanceof Date) ? time : (typeof time === 'number') ? new Date(time) : new Date((time || '').replace(/-/g, '/'))
  let diff = (((new Date()).getTime() - date.getTime()) / 1000)
  let dayDiff = Math.floor(diff / 86400)
  let isValidDate = Object.prototype.toString.call(date) === '[object Date]' && !isNaN(date.getTime())
  if (!isValidDate) {
    console.error('not a valid date')
  }
  const formatDate = function (date, withTime) {
    let today = new Date(date)
    let year = today.getFullYear()
    let month = ('0' + (today.getMonth() + 1)).slice(-2)
    let day = ('0' + today.getDate()).slice(-2)
    let hour = today.getHours()
    let minute = today.getMinutes()
    let second = today.getSeconds()
    return withTime ? `${year}-${month}-${day} ${hour}:${minute}:${second}` : `${year}-${month}-${day}`
  }
  if (isNaN(dayDiff) || dayDiff < 0 || dayDiff >= 30) {
    return formatDate(date, withTime)
  }
  /* eslint no-mixed-operators: 0 */
  return dayDiff === 0 && (
      diff < 60 && '刚刚' ||
      diff < 120 && '1分钟前' ||
      diff < 3600 && Math.floor(diff / 60) + '分钟前' ||
      diff < 7200 && '1小时前' ||
      diff < 86400 && Math.floor(diff / 3600) + '小时前') ||
    dayDiff === 1 && '昨天' ||
    dayDiff < 7 && dayDiff + '天前' ||
    dayDiff < 30 && Math.ceil(dayDiff / 7) + '周前'
}
friendlyTime('2018-1-1 18:00:00') // "4周前"
friendlyTime('2018-1-27 18:00:00') // "2天前"
friendlyTime('2018-1-29 18:00:00') // "17小时前"
friendlyTime('2017-10-01 18:00:00', true) // "2017-10-01 18:0:0"

参考:

MIT Licensed | Copyright © 2018-present 滇ICP备16006294号

Design by Quanzaiyu | Power by VuePress