js获取本月,本年,近一月,近3月,近1年的日期范围,获取近n月的日期范围

站长软件开发4个月前技术分享368
js获取本月,本年,近一月,近3月,近1年的日期范围,获取近n月的日期范围

js获取本月,本年,近一月,近3月,近1年的日期范围,获取近n月的日期范围

function getnMonth(i) {
  console.log("获取近i月的时间段", i)
  var now = new Date()
  var year = now.getFullYear()
  var month = now.getMonth() + 1;
  var newmonth=month < 10 ? "0" + month : month
  var day = now.getDate()
  var dateObj = {}
  dateObj.endTime = year + "-" + newmonth + "-" + day
  var nowMonthDay = new Date(year, month, 0).getDate() //当前月的总天数
  if (i == 12) {
    //如果是12月,年数往前推一年<br>
    dateObj.startTime = year - 1 + "-" + newmonth + "-" + day
  } else if (month - i <= 0) {
    // 如果前推i月小于0,年数往前推一年<br>
    dateObj.startTime = year - 1 + "-" + (12+month-i) + "-" + day
  } else {
    var endTimeMonthDay = new Date(year, parseInt(month) - i, 0).getDate()
    if (endTimeMonthDay < day) {
      // i个月前所在月的总天数小于现在的天日期
	  let mon=month - i;
	  mon1=mon < 10 ? "0" + mon : mon
      if (day < nowMonthDay) {
        // 当前天日期小于当前月总天数
        dateObj.startTime = year + "-" + mon1 + "-" + (endTimeMonthDay - (nowMonthDay - day))
      } else {
        dateObj.startTime = year + "-" +mon1+ "-" + endTimeMonthDay
      }
    } else {
      dateObj.startTime = year + "-" + mon1 + "-" + day
    }
  }
  return [dateObj.startTime,dateObj.endTime]
}
getnMonth(3)//获取近3月时间段
//['2023-11-23', '2024-01-23']

获取当月、当年时间范围:

/**
 * 当月
 * @param {Date} date
 * @returns {String} 当月
 */
export function getCurmonth(date) {
  const time = date ? new Date(date) : new Date()
  const y = time.getFullYear()
  let m = time.getMonth() + 1  
  let d = time.getDate()
  m = m < 10 ? "0" + m : m
  const d1 = "01"
  return [[y, m, d1].join("-"),[y, m, d].join("-")]
}
/**
 * 当年
 * @param {Date} date
 * @returns {String} 当年
 */
export function getCuryear(date) {
  const time = date ? new Date(date) : new Date()
  const y = time.getFullYear()
  let m = "1"; 
  let m1 = time.getMonth() + 1  
  let d = time.getDate()
  m = m < 10 ? "0" + m : m
  const d1 = "01"
  return [[y, m, d1].join("-"),[y, m, d].join("-")]
}


联系站长:

相关文章

Animate.css使用方法,及源码下载,包含中文文档教程-css3动画演示合集,可用于uniapp

Animate.css使用方法,及源码下载,包含中文文档教程-css3动画演示合集,可用于uniapp

Animate.css是一个即用型跨浏览器动画库,可在您的 Web 项目中使用。非常适合强调、主页、滑块和注意力引导提示。注意:Animate.css可以在uniapp中使用,并且兼容多端,源码放页面...

js实用函数之map()函数的使用,一分钟学会

js实用函数之map()函数的使用,一分钟学会

重点:map() 方法定义在JavaScript的Array中,它返回一个新的数组,数组中的元素为原始数组调用函数处理后的值。值得注意的是:1、map()函数不会对空数组进行检测;2、map...

vue history路由下,对ngnix服务配置修改防止出现404问题

vue history路由下,对ngnix服务配置修改防止出现404问题

打开配置文件: # 打开配置文件 vi /usr/local/nginx/conf/nginx.con 宝塔则点击域名在里面找到配置文件进去修改: 如果域名直接指向...

原生js把时间戳转为日期格式年月日时分秒

原生js把时间戳转为日期格式年月日时分秒

原生js把时间戳转为日期格式年月日时分秒function parsetime(timestamp){     let timelength...

php根据id和pid把单级数组重新组合为树结构

php根据id和pid把单级数组重新组合为树结构

function list_to_trees($list, $pk='id', $pid = 'pid', $child =&nb...

【JavaScript】js获取当前年月日周

【JavaScript】js获取当前年月日周

【JavaScript】js获取当前年月日周function getcurtime(){     const addZero =...

发表评论    

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。