js 根据当前日期获取过去n天前的时间 YYYY-MM-DD 年月日

最近在做项目时,有一个要处理根据当前时间往前推算:3个月前,半年前,一年前的一个业务场景,于是就自己整理了下这个处理的工具函数:

function beforeDays(num) {
  // 设置日期,当前日期的前num天
  let myDate = new Date() // 获取今天日期
  myDate.setDate(myDate.getDate() - (num - 1))
  let dateArray = []
  let myMonth = myDate.getMonth() + 1
  if (myMonth >= 1 && myMonth <= 9) {
    myMonth = '0' + myMonth
  }
  let myDates = myDate.getDate()
  if (myDates >= 0 && myDates <= 9) {
    myDates = '0' + myDates
  }
  let dateTemp
  let flag = 1
  for (let i = 0; i < num; i++) {
    dateTemp = myDate.getFullYear() + '-' + myMonth + '-' + myDates
    dateArray.push(dateTemp)
    myDate.setDate(myDate.getDate() + flag)
  }
  return dateArray[0]
}

获取当前日期 时间格式 YYYY-MM-DD

function getCurrentDate() {
  var date = new Date()
  var seperator1 = '-'
  var year = date.getFullYear()
  var month = date.getMonth() + 1
  var strDate = date.getDate()
  if (month >= 1 && month <= 9) {
    month = '0' + month
  }
  if (strDate >= 0 && strDate <= 9) {
    strDate = '0' + strDate
  }
  var currentdate = year + seperator1 + month + seperator1 + strDate
  return currentdate
}

除此之外还有一种业务场景要处理数据格式:

将:
“150000,150300,150303” ====> [“150000”, “150300”, “150303”]

则直接使用:

let str = “150000,150300,150303”
console.log(str.split(’,’))

===> [“150000”, “150300”, “150303”]

业务场景2:

let str1 = “河北省/石家庄市/长安区|太和路08号”
截取 | 之后的内容

console.log(str1.split(’|’))
// [“河北省/石家庄市/长安区”, “太和路08号”]
转换成数组,然后根据数组索引取出对应的内容即可

业务场景3:
有一个关于省/市/区的一个 cascader级联选择器,要将数据处理成以 ‘/’分割的形式传给后台

let dz = this.$refs[‘Cascader’].currentLabels.join(’/’).replace(/,/g, ‘’) + ‘|’ + this.form.addressDetails

这种形式:
“河北省/石家庄市/长安区|太和路08号”

此外,数组和字符串常用的转换还包括:
join() 方法是数组的方法,表示元素之前用什么拼接为字符串
split() 方法是字符串的方法,表示用什么去切割字符串为数组

比如:
const arr = [1, 2, 3, 4, 5]
// 元素以‘,’分割,然后以逗号切割为字符串数组
arr.join(‘,’).split(’,’)
// [“1”, “2”, “3”, “4”, “5”]

猜你喜欢

转载自blog.csdn.net/qyl_0316/article/details/106112467