zoukankan      html  css  js  c++  java
  • [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
    }
    
    
    坚持,坚持,坚持。再坚持坚持!
  • 相关阅读:
    C++中的字符串可以这样换行写
    2020年最受欢迎的 10 门编程语言
    10 本最适合初学者和高级程序员的Python书籍
    手把手教你用 Python + Flask 搭建个人博客
    CentOS VS Ubuntu,谁才是更好的 Linux 版本?
    Python丨为什么你学不好设计模式?
    突破C++瓶颈,在此一举!
    从零上手 GDB 调试,看这个教程就够了~
    搞机器学习需要数学基础吗?
    用 Python 读写 Excel 表格,就是这么的简单粗暴且乏味
  • 原文地址:https://www.cnblogs.com/danker/p/13305802.html
Copyright © 2011-2022 走看看