[Date][JavaScript][JS]常用日期格式类总结

格式化日期

formatDate.js

// 日期格式化处理
const padLeftZero = function(str) {
  return ('00' + str).substr(str.length)
}

const formatDate = function(date, fmt) {
  if (!date) return ''
  if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length))
  const o = {
    'M+': date.getMonth() + 1,
    'd+': date.getDate(),
    'h+': date.getHours(),
    'm+': date.getMinutes(),
    's+': date.getSeconds(),
    'S': date.getMilliseconds() // 毫秒
  }
  for (const k in o) {
    if (new RegExp(`(${k})`).test(fmt)) {
      const str = o[k] + ''
      fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? str : padLeftZero(str))
    }
  }
  return fmt
}

export default formatDate

计算获取某一天日期

getSomeDate.js

import formatDate from './formatDate'
/*
@param d 日期 Date()实例
@param N 数量 Number
@param ftm 期望格式化结果,如'yyyy-MM-dd hh:mm:ss'
*/
// 获取给定日期的N个月前的日期
function getBeforeMonthsDate(d, N, ftm) {
  d.setMonth(d.getMonth() - N)
  return formatDate(d, ftm)
}

// 获取给定日期的N天后的日期
function getAfterDaysDate(d, N, ftm) {
  return formatDate(new Date(d.getTime() + N * 24 * 60 * 60 * 1000), ftm)
}

// 获取给定日期的N天前的日期d
function getBeforeDaysDate(d, N, ftm) {
  return formatDate(new Date(d.getTime() - N * 24 * 60 * 60 * 1000), ftm)
}

// 获取给定日期的N年后的日期
function getAfterYearsDate(d, N, ftm) {
  d.setFullYear(d.getFullYear() + N)
  return formatDate(d, ftm)
}

// 获取给定日期的N年前的日期
function getBeforeYearsDate(d, N, ftm) {
  d.setFullYear(d.getFullYear() - N)
  return formatDate(d, ftm)
}

export default {
  getAfterMonthsDate: getAfterMonthsDate,
  getBeforeMonthsDate: getBeforeMonthsDate,
  getAfterDaysDate: getAfterDaysDate,
  getBeforeDaysDate: getBeforeDaysDate,
  getAfterYearsDate: getAfterYearsDate,
  getBeforeYearsDate: getBeforeYearsDate
}

posted @ 2020-07-15 15:32  丹哥不是哥  阅读(318)  评论(0编辑  收藏  举报