js实现获取当前时间,本月,本年的时间段,并进行格式化

废话少说上代码

首先我们先写一段可以用于格式化时间的代码:格式为yy-mm-dd

// 格式化时间
    formatTime(time) {
      const timer = new Date(time)
      const year = timer.getFullYear()
      const mouth = timer.getMonth() + 1 > 10 ? timer.getMonth() + 1 : '0' + (timer.getMonth() + 1)
      const date = timer.getDate() > 10 ? timer.getDate() : '0' + timer.getDate()
      return year + '-' + mouth + '-' + date
    },

我们还需要一个传入年份和月份,返回给我们这个月有多少天的方法

lastDay(Year, Moon) {
      return new Date(Year, Moon, 0).getDate()
    },

之后我们编写获取时间的代码,并将其保存起来,当页面进入时,在create()中调用

getTime() {
      this.now = new Date() // 当前日期
      this.nowDay = this.now.getDate() // 当前日
      this.nowDayOfWeek = this.now.getDay() // 今天本周的第几天
      this.nowMonth = this.now.getMonth() // 当前月
      this.nowYear = this.now.getFullYear() // 当前年
    },

然后获取本周的时间段

// 获得本周的开端日期
    getWeekStartDate(nowDay, nowMonth, nowYear, nowDayOfWeek) {
      const weekStartDate = new Date(nowYear, nowMonth, nowDay - nowDayOfWeek + 1)
      return this.formatTime(weekStartDate)
    },
    // 获得本周的停止日期
    getWeekEndDate(nowDay, nowMonth, nowYear, nowDayOfWeek) {
      const weekEndDate = new Date(nowYear, nowMonth, nowDay + (6 - nowDayOfWeek + 1))
      return this.formatTime(weekEndDate)
    }

获取本月的时间段

// 获得本月的开端日期
    getMonthStartDate(nowYear, nowMonth) {
      const monthStartDate = new Date(nowYear, nowMonth, 1)
      return this.formatTime(monthStartDate)
    },
    // 获得本月的停止日期
    getMonthEndDate(nowYear, nowMonth) {
      const monthEndDate = new Date(nowYear, nowMonth, this.lastDay(this.nowYear, this.nowMonth) - 1)
      return this.formatTime(monthEndDate)
    }

获取年的时间段

// 获得本年的开端日期
    getYearStartDate(nowYear) {
      const YearStartDate = new Date(nowYear, 0, 1)
      return this.formatTime(YearStartDate)
    },
    // 获得本年的开端日期
    getYearEndDate(nowYear) {
      const YearStartDate = new Date(nowYear, 11, 31)
      return this.formatTime(YearStartDate)
    }

完事!

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值