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
    }
    
    
    坚持,坚持,坚持。再坚持坚持!
  • 相关阅读:
    测试:安装测试用例
    测试:界面测试
    软件项目管理:什么是baseline
    测试:fiddler使用
    android adb常用指令
    sqlite语句主页
    几条常见的数据库分页 SQL 语句
    linux下tomcat无法访问问题(换一种说法:无法访问8080端口)
    eclipse中svn的各种状态图标详解
    Tomcat项目部署方式
  • 原文地址:https://www.cnblogs.com/danker/p/13305802.html
Copyright © 2011-2022 走看看