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

站长软件开发9个月前技术分享670
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("-")]
}


联系站长:

相关文章

【简单一行】使用js去掉空格方法-原生js代码实现JavaScript

【简单一行】使用js去掉空格方法-原生js代码实现JavaScript

【简单一行】使用js去掉空格方法-原生js代码实现JavaScript str为要去除空格的字符串:1、去掉所有空格:str=str.replace(/\s+/g,"");  &...

uniapp富文本编辑器editor的使用,复制可用

uniapp富文本编辑器editor的使用,复制可用

关于uniapp富文本编辑器editor的使用,我会把HTML,css,js三部分代码都完整列出来,其实也是一个总结,因为官方教程有些不是很清楚,这里总结一下,方便大家使用:1、html部分:<...

js获取m到n随机数,js获取随机整数,从0到10,从m到n任意数

js获取m到n随机数,js获取随机整数,从0到10,从m到n任意数

˂a class="reference-link" name="js获取从m到n的随机数"˃js获取从m到n的随机数function getRandomNumber(min, ma...

css显示三行文字,溢出显示省略号

css显示三行文字,溢出显示省略号

css显示三行文字,溢出显示省略号(显示任意行,可以把数字3替换成其他数字):.text-wrap {   display: -webkit-box; &n...

js把数字格式化为千分位兼容版,兼容小数(8,888.22)

js把数字格式化为千分位兼容版,兼容小数(8,888.22)

js把任意数字格式化为千分位/**  * 格式化为千分位  * @param num 当前值字符串  * @ret...

发表评论    

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