js时间获取格式(获取前几日、月、年方法)

获取当前时间

//获取当前时间    
var date = new Date()

//设置当前时间格式
date.Format("yyyy-MM-dd hh:mm:ss")
//(new Date()).Format("yyyy-MM-dd hh:mm:ss") ==> 2019-01-02 10:19:04

//获取当前时间年
date.getFullYear()
//设置当前年份
date.setYear(date.getFullYear() - 1)

//获取当前时间月(月份记得加1,返回月份从0开始-----[0~11])
date.getMonth() + 1
//设置当前月份
date.setMonth(date.getMonth() - 1)

//获取当前时间日
date.getDate()
//设置当前日
date.setDate(date.getDate() - 1)

//获取前几年日期
//numOfDays:往前数几年
//返回值举例:[2024,2023,2022]
    getYearsDate(numOfDays) {
      let num = []
      var date = new Date()
      num.push(date.getFullYear().toString())
      for (let index = 1; index < numOfDays; index++) {
        date.setYear(date.getFullYear() - 1)
        var year = date.getFullYear()
        num.push(year.toString())
      }
      return num
    },


//获取前几月日期
//numOfDays:往前数几月
//返回值举例:[2024-1,2023-1,2022-1]
    getMonthDate(numOfDays) {
      var date = new Date()
      let num = []
      num.push(date.getFullYear() + '-' + (date.getMonth() + 1))
      for (let index = 1; index < numOfDays; index++) {
        date.setMonth(date.getMonth() - 1)
        var year = date.getMonth() + 1
        num.push(date.getFullYear() + '-' + year)
      }
      return num
    },

//获取前几日日期
//numOfDays:往前数几日
//返回值举例:[2024-1-1,2023-1-1,2022-1-1]
    getDayDate(numOfDays) {
      var date = new Date()
      let num = []
      num.push(date.getFullYear() + '-' + (date.getMonth() + 1) + '-' + date.getDate())
      for (let index = 1; index < numOfDays; index++) {
        date.setDate(date.getDate() - 1)
        var year = date.getDate()
        num.push(date.getFullYear() + '-' + (date.getMonth() + 1) + '-' + year)
      }
      return num
    },

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值