获取下周、下月时间

import moment from "moment";
// 时间
var now = new Date(); // 当前日期
var nowDayOfWeek = now.getDay(); // 今天本周的第几天
var nowDay = now.getDate();    // 当前日期
var nowMonth = now.getMonth(); // 当前月
var nowYear = now.getYear();   // 当前年
 export function getTime(value){
    nowYear += (nowYear < 2000) ? 1900 : 0; 
    //获得下周开始时间
    var weekStartDate = new Date(nowYear, nowMonth, nowDay - nowDayOfWeek + 8);
    //获得下周结束时间
    var weekEndDate = new Date(nowYear, nowMonth, nowDay + (6 - nowDayOfWeek) + 8);
    //获得下月开始时间
    var weekStartDate = new Date(nowYear, nowMonth, nowDay - nowDayOfWeek + 8);
    //获得下月结束时间
    var weekEndDate = new Date(nowYear, nowMonth, nowDay + (6 - nowDayOfWeek) + 8);
    if(value=="下周"){
      return moment(weekStartDate).format("YYYY-MM-DD") + "," + moment(weekEndDate).format("YYYY-MM-DD");
    }else if(value=="下月"){
      return nextMonthFirstDay() + "," + nextMonthLastDay()
    }
  }
  /*获取下个月的第一天*/
  export function  nextMonthFirstDay() {
    var time = new Date();
    var year = time.getFullYear();
    var month = time.getMonth() + 2;
    if (month > 12) {
      month = month - 12;
      year = year + 1;
    }
    var day = 1;
    return year + '-' + month + '-' + day;
  }
  /*获取下个月的最后一天*/
  export function nextMonthLastDay() {
    var time = new Date();
    var year = time.getFullYear();
    var month = time.getMonth() + 2;
    if (month > 12) {
      month = month - 12;
      year = year + 1;
    }
    var day = nextMonthDay(year, month);
    return year + '-' + month + '-' + day;
  }
  //判断每月多少天
  export function nextMonthDay(year, month) {
    var day31 = [1, 3, 5, 7, 8, 10, 12];
    var day30 = [4, 6, 9, 11];
    if (day31.indexOf(month) > -1) {
      return 31;
    } else if (day30.indexOf(month) > -1) {
      return 30;
    } else {
      if (isLeapYear(year)) {
        return 29;
      } else {
        return 28;
      }
    }
  }
  //判断是否为闰年
  export function isLeapYear(year) {
    return (year % 4 == 0) && (year % 100 != 0 || year % 400 == 0);
  }

以上代码封装为一个文件 再需要使用的文件中引入

直接传入value使用即可 

代码中引用的moment是一个第三方插件,格式化日期的,也可手写格式化日期的函数。如下:

传入日期即可

getFormatDate: function (nowDate) {
        var year = nowDate.getFullYear();
        var month = nowDate.getMonth() + 1 < 10 ? "0" + (nowDate.getMonth() + 1) : nowDate.getMonth() + 1;
        var date = nowDate.getDate() < 10 ? "0" + nowDate.getDate() : nowDate.getDate();
        var hour = nowDate.getHours()< 10 ? "0" + nowDate.getHours() : nowDate.getHours();
        var minute = nowDate.getMinutes()< 10 ? "0" + nowDate.getMinutes() : nowDate.getMinutes();
        var second = nowDate.getSeconds()< 10 ? "0" + nowDate.getSeconds() : nowDate.getSeconds();
        return year + "-" + month + "-" + date+" "+hour+":"+minute+":"+second;
},

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值