【最全日期获取合集】js获取昨天,今天,明天,上周,本周,下周,上月,本月,下月,去年,本年,明年,上季度,本季度,下季度,向前推日期等【全覆盖,拿来即用】

前言

最近经常做到这个功能,就是需要给后台传日期
然后需求是需要分出几个按钮,点击后传给后端 周,月,季度,年等时间
我就网上看了一下功能,发现很多写的不够全,都是几个几个的。
这里就干脆整理一个合集出来,把所有时间的按钮都放里面,也方便以后使用直接复制。
这里我是配合的elementul的日期选择器使用的,因为很多人都用这个
当然不适用也是可以直接获取到日期的。

功能简介

这里按钮有上 本 下 这样的,都是完整的日期。然后是根据传参数直接拿到的日期。
参数是这样的:-1代表上,0代表本,1代表下。
其中有一些按钮要介绍一下,比如有一个本月的按钮我括号标出来了,1号到今天。
意思就是比如今天是9月6号,那点击这个获取的是9月1号到9月6号得。
但是如果点完整月的本月按钮,获取的是9月1到9月30的日期。
然后有一个向前推的按钮,也就是最近七天和最近三十天。
这两个按钮参数穿的是你要向前推的日期数。你传10就是向前十天,15就是15天。就这个意思。
日期转换格式的方法也有,两种转化的方法在最下面。

效果图

我按顺序点了一遍,从左到右哈,自己对比一下好了
【最全日期获取合集】js获取昨天,今天,明天,上周,本周,下周,上月,本月,下月,去年,本年,明年,上季度,本季度,下季度,向前推日期等【全覆盖,拿来即用】_第1张图片

2023-2-13更新(新增了六个查询,年龄查询,星座查询,输入日期和当前日期时间差,两个日期间隔天数,输入日期的月份总天数,本月过去天数)

下方的代码我已经更新成新的了。
在这里插入图片描述

代码部分

建议拿到后复制到自己的vue内查看格式更好,把所有的方法收起来看比较好看一点,我都有注释的,一看就知道了

我对于按钮触发方法都直接用【】注释标出来了,可以直接找到。

<template>
  <div style="padding: 40px">
    <el-date-picker
      v-model="timerValue"
      value-format="yyyy-MM-dd"
      type="daterange"
      range-separator="至"
      start-placeholder="开始日期"
      end-placeholder="结束日期"
      style="margin-right: 20px"
    >
    </el-date-picker>
    <div style="margin-top: 20px">
      <el-button type="primary" size="mini" @click="submitTimejt(-1)"
        >昨日</el-button
      >
      <el-button type="primary" size="mini" @click="submitTimejt(0)"
        >今日</el-button
      >
      <el-button type="primary" size="mini" @click="submitTimejt(1)"
        >明日</el-button
      >
      <el-button type="primary" size="mini" @click="submitTime(7)"
        >最近一周(向前推)</el-button
      >
      <el-button type="primary" size="mini" @click="submitTime(30)"
        >最近30天(向前推)</el-button
      >
      <el-button type="primary" size="mini" @click="getWeektime(-1)"
        >上周</el-button
      >
      <el-button type="primary" size="mini" @click="getWeektime(0)"
        >本周</el-button
      >
      <el-button type="primary" size="mini" @click="getWeektime(1)"
        >下周</el-button
      >
      <el-button type="primary" size="mini" @click="submitTimeSy(-1)"
        >上月(完整月)</el-button
      >
      <el-button type="primary" size="mini" @click="submitTimeSy(0)"
        >本月(完整月)</el-button
      >
      <el-button type="primary" size="mini" @click="submitTimeSy(1)"
        >下月(完整月)</el-button
      >
      <el-button type="primary" size="mini" @click="submitTimeBy"
        >本月(1号到今天)</el-button
      >
      <el-button type="primary" size="mini" @click="checkQuartertimer(-1)"
        >上季度</el-button
      >
      <el-button type="primary" size="mini" @click="checkQuartertimer(0)"
        >本季度</el-button
      >
      <el-button type="primary" size="mini" @click="checkQuartertimer(1)"
        >下季度</el-button
      >
      <el-button type="primary" size="mini" @click="getYeartimer(-1)"
        >去年</el-button
      >
      <el-button type="primary" size="mini" @click="getYeartimer(0)"
        >本年</el-button
      >
      <el-button type="primary" size="mini" @click="getYeartimer(1)"
        >明年</el-button
      >
      <el-button type="primary" size="mini" @click="checkQuarter"
        >当前是第几季度</el-button
      >
      <el-button type="primary" size="mini" @click="queryQonstellation"
        >计算输入日期是什么星座</el-button
      >
      <el-button type="primary" size="mini" @click="timeDifference"
        >计算输入日期和当前日期的时间差</el-button
      >
      <el-button type="primary" size="mini" @click="queryAge"
        >查询年龄</el-button
      >
      <el-button type="primary" size="mini" @click="daysOfInquiry"
        >两个日期间隔天数</el-button
      >
      <el-button type="primary" size="mini" @click="daysOfTheMonth"
        >查询输入日期的月总天数</el-button
      >
      <el-button type="primary" size="mini" @click="daysPast"
        >查询本月过去天数</el-button
      >
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      //日期
      timerValue: "",
    };
  },
  methods: {
    //查看日期
    log() {
      console.log(this.timerValue, "日期值");
    },
    // 【查询星座】获取传入日期是什么星座的
    queryQonstellation() {
      // let time='2023-2-13'
      let time = new Date();
      console.log(this.getHoroscope(time), "查询星座");
    },
    // 【输入日期和当前日期的时间差】
    timeDifference() {
      let time = "2023-2-11";
      console.log(this.sumAge(time), "时间差,我模拟的数据是2023-2-11");
    },
    // 【查询年龄】
    queryAge() {
      let time = "1997-2-11";
      console.log(
        this.getAgeByBirthday(time),
        "查询年龄,我模拟的数据是1997-2-11"
      );
    },
    // 【查询两个日期间隔天数】
    daysOfInquiry() {
      let time = this.getDiffDay('2023-2-10', '2023-2-15') + 1; //这里加一天是算上了当天的,不是单纯的15减10(正常日期应该是10,11,12,13,14,15)
      console.log(time,'两个日期间隔天数');
    },
    // 【查询输入的日期月有多少天,或者查询当前月过去了多少天】
    daysOfTheMonth(){
      let time='2023-2-10'
      let dt = time.split("-");//拆分成数组
      let tsdate = new Date(dt[0], dt[1], 0).getDate();//这里就是0是拿的年,1拿的月
      console.log(tsdate,'输入日期的月总天数,我模拟数据2023-2-10');
    },
    // 【查询本月过去了多少天】
    daysPast(){
      let tsdate = new Date().getDate();//这里不输入值就是查询当月的过去天数
      console.log(tsdate,'本月过去天数');
    },
    //【获取n天前时间】: 传参数几就是今天往前推几天的日期。比如传7就是往前七天的日期
    submitTime(n) {
      //开始时间
      var nowDate = new Date();
      let befDate = new Date(nowDate.getTime() - n * 24 * 3600 * 1000);
      let byear = befDate.getFullYear();
      let bmonth = befDate.getMonth() + 1;
      if (bmonth >= 1 && bmonth <= 9) {
        bmonth = "0" + bmonth;
      }
      let bday = befDate.getDate();
      if (bday >= 0 && bday <= 9) {
        bday = "0" + bday;
      }
      //截止时间
      let endDate = new Date(nowDate.getTime() - 1 * 24 * 3600 * 1000);
      let year = endDate.getFullYear();
      let month = endDate.getMonth() + 1;
      if (month >= 1 && month <= 9) {
        month = "0" + month;
      }
      let day = endDate.getDate();
      if (day >= 0 && day <= 9) {
        day = "0" + day;
      }

      //赋值
      let that = this;
      that.timerValue = [
        byear + "-" + bmonth + "-" + bday,
        year + "-" + month + "-" + day,
      ];
      this.log();
    },
    //【查询当前第几季度】
    checkQuarter() {
      console.log(this.getQuarterByMonth());
    },
    //【本月】:当前月1号到今天
    submitTimeBy() {
      let that = this;
      var date = new Date();
      var month = parseInt(date.getMonth() + 1);
      var day = date.getDate();
      if (month < 10) month = "0" + month;
      let yuechu = date.getFullYear() + "-" + month + "-" + "01";
      if (day == 1) {
        that.timerValue = [yuechu, yuechu];
      } else {
        day = day - 1;
        if (day < 10) day = "0" + day;
        let yuedi = date.getFullYear() + "-" + month + "-" + day;
        that.timerValue = [yuechu, yuedi];
      }
      that.log();
    },

    //-------------------------日周月季年,第一个参数:开始时间(s)结束时间(e),第二个参数:上(-1)本(0)下(1)
    //【昨天,今天,明天】
    submitTimejt(num) {
      let value = this.getDate(num);
      this.timerValue = [value, value];
      this.log();
    },
    //【去周,本周,下周】
    getWeektime(num) {
      let s = this.getMonday("s", num);
      let e = this.getMonday("e", num);
      this.timerValue = [s, e];
      this.log();
    },
    //【上月,本月,下月】:1号到月底
    submitTimeSy(num) {
      let s = this.getMonth("s", num);
      let e = this.getMonth("e", num);
      this.timerValue = [s, e];
      this.log();
    },
    //【上季度,本季度,下季度】参数:-1是上季度,0是本季度,1是下季度
    checkQuartertimer(num) {
      if (num == -1) {
        let s = this.getDayTimer(this.getLastQuarterStartDate());
        let e = this.getDayTimer(this.getLastQuarterEndDate());
        this.timerValue = [s, e];
        this.log();
        return;
      } else if (num == 0) {
        let s = this.getDayTimer(this.getQuarterMonth("s"));
        let e = this.getDayTimer(this.getQuarterMonth("e"));
        this.timerValue = [s, e];
        this.log();
        return;
      } else if (num == 1) {
        let s = this.getDayTimer(this.getNextQuarterStartDate());
        let e = this.getDayTimer(this.getNextQuarterEndDate());
        this.timerValue = [s, e];
        this.log();
        return;
      }
    },
    //【去年,本年,明年】
    getYeartimer(num) {
      let s = this.getYear("s", num);
      let e = this.getYear("e", num);
      this.timerValue = [s, e];
      this.log();
    },

    //日获取
    getDate(dates) {
      var dd = new Date();
      var n = dates || 0;
      dd.setDate(dd.getDate() + n);
      var y = dd.getFullYear();
      var m = dd.getMonth() + 1;
      var d = dd.getDate();
      m = m < 10 ? "0" + m : m;
      d = d < 10 ? "0" + d : d;
      var day = y + "-" + m + "-" + d;
      return day;
    },
    //周获取
    getMonday(type, dates) {
      var now = new Date();
      var nowTime = now.getTime();
      var day = now.getDay();
      var longTime = 24 * 60 * 60 * 1000;
      var n = longTime * 7 * (dates || 0);
      if (type == "s") {
        var dd = nowTime - (day - 1) * longTime + n;
      }
      if (type == "e") {
        var dd = nowTime + (7 - day) * longTime + n;
      }
      dd = new Date(dd);
      var y = dd.getFullYear();
      var m = dd.getMonth() + 1;
      var d = dd.getDate();
      m = m < 10 ? "0" + m : m;
      d = d < 10 ? "0" + d : d;
      var day = y + "-" + m + "-" + d;
      return day;
    },
    //月度获取
    getMonth(type, months) {
      var d = new Date();
      var year = d.getFullYear();
      var month = d.getMonth() + 1;
      if (Math.abs(months) > 12) {
        months = months % 12;
      }
      if (months != 0) {
        if (month + months > 12) {
          year++;
          month = (month + months) % 12;
        } else if (month + months < 1) {
          year--;
          month = 12 + month + months;
        } else {
          month = month + months;
        }
      }
      month = month < 10 ? "0" + month : month;
      var date = d.getDate();
      var firstday = year + "-" + month + "-" + "01";
      var lastday = "";
      if (
        month == "01" ||
        month == "03" ||
        month == "05" ||
        month == "07" ||
        month == "08" ||
        month == "10" ||
        month == "12"
      ) {
        lastday = year + "-" + month + "-" + 31;
      } else if (month == "02") {
        if (
          (year % 4 == 0 && year % 100 != 0) ||
          (year % 100 == 0 && year % 400 == 0)
        ) {
          lastday = year + "-" + month + "-" + 29;
        } else {
          lastday = year + "-" + month + "-" + 28;
        }
      } else {
        lastday = year + "-" + month + "-" + 30;
      }
      var day = "";
      if (type == "s") {
        day = firstday;
      } else {
        day = lastday;
      }
      return day;
    },
    //季度获取
    getQuarterMonth(type) {
      var now = new Date();
      var nowMonth = now.getMonth();
      var year = now.getFullYear();
      var quarterStartMonth = 1;
      if (nowMonth < 3) {
        quarterStartMonth = 1;
      }
      if (2 < nowMonth && nowMonth < 6) {
        quarterStartMonth = 4;
      }
      if (5 < nowMonth && nowMonth < 9) {
        quarterStartMonth = 7;
      }
      if (nowMonth > 8) {
        quarterStartMonth = 10;
      }
      if (type == "s") {
        var day = year + "-" + quarterStartMonth + "-01";
      } //1-3 4-6 7-9 10-12
      if (type == "e") {
        if (quarterStartMonth == 1) {
          var day = year + "-" + (quarterStartMonth + 2) + "-31";
        }
        if (quarterStartMonth == 10) {
          var day = year + "-" + (quarterStartMonth + 2) + "-31";
        }
        if (quarterStartMonth == 4) {
          var day = year + "-" + (quarterStartMonth + 2) + "-30";
        }
        if (quarterStartMonth == 7) {
          var day = year + "-" + (quarterStartMonth + 2) + "-30";
        }
      }
      return day;
    },
    //年度获取
    getYear(type, dates) {
      var dd = new Date();
      var n = dates || 0;
      var year = dd.getFullYear() + Number(n);
      if (type == "s") {
        var day = year + "-01-01";
      }
      if (type == "e") {
        var day = year + "-12-31";
      }
      if (!type) {
        var day = year + "-01-01/" + year + "-12-31";
      }
      return day;
    },
    //上个季度开始时间
    getLastQuarterStartDate() {
      var now = new Date();
      var nowYear = now.getFullYear(); //当前年
      return new Date(nowYear, this.getQuarterStartMonth() - 3, 1);
    },
    //上个季度结束时间
    getLastQuarterEndDate() {
      var quarterEndMonth = this.getQuarterStartMonth() - 1;
      var now = new Date();
      now.setMonth(quarterEndMonth);
      var nowMonth = now.getMonth();
      var nowYear = now.getFullYear();
      return new Date(
        nowYear,
        quarterEndMonth,
        this.getMonthDays(quarterEndMonth)
      );
    },
    //下个季度开始时间
    getNextQuarterStartDate() {
      var now = new Date();
      var nowYear = now.getFullYear(); //当前年
      return new Date(nowYear, this.getQuarterStartMonth() + 3, 1);
    },
    //下个季度结束时间
    getNextQuarterEndDate() {
      var quarterEndMonth = this.getQuarterStartMonth() + 5;
      var now = new Date();
      now.setMonth(quarterEndMonth);
      var nowMonth = now.getMonth();
      var nowYear = now.getFullYear();
      return new Date(
        nowYear,
        quarterEndMonth,
        this.getMonthDays(quarterEndMonth)
      );
    },
    //获得本季度的开始月份
    getQuarterStartMonth() {
      var nowMonth = new Date().getMonth();
      var quarterStartMonth = 0;
      if (nowMonth < 3) {
        quarterStartMonth = 0;
      }
      if (2 < nowMonth && nowMonth < 6) {
        quarterStartMonth = 3;
      }
      if (5 < nowMonth && nowMonth < 9) {
        quarterStartMonth = 6;
      }
      if (nowMonth > 8) {
        quarterStartMonth = 9;
      }
      return quarterStartMonth;
    },
    //获得某月的天数
    getMonthDays(myMonth) {
      var nowYear = new Date().getFullYear(); //当前年
      var monthStartDate = new Date(nowYear, myMonth, 1);
      var monthEndDate = new Date(nowYear, myMonth + 1, 1);
      var days = (monthEndDate - monthStartDate) / (1000 * 60 * 60 * 24);
      return days;
    },

    // 【时间格式转换 YYYY-MM-DD】
    getDayTimer(data) {
      var date = new Date(data);
      var y = date.getFullYear();
      var m = date.getMonth() + 1;
      m = m < 10 ? "0" + m : m;
      var d = date.getDate();
      d = d < 10 ? "0" + d : d;
      var currentdate = y + "-" + m + "-" + d;
      return currentdate;
    },
    // 【时间格式转换 YYYY-MM-DD hh:mm:ss】
    getDayTimerHms(data) {
      var date = new Date(data);
      var y = date.getFullYear();
      var m = date.getMonth() + 1;
      m = m < 10 ? "0" + m : m;
      var d = date.getDate();
      d = d < 10 ? "0" + d : d;
      var currentdate = y + "-" + m + "-" + d;
      var hh = date.getHours();
      hh = hh < 10 ? "0" + hh : hh;
      var mm = date.getMinutes();
      mm = mm < 10 ? "0" + mm : mm;
      var ss = date.getSeconds();
      ss = ss < 10 ? "0" + ss : ss;
      var time = hh + ":" + mm + ":" + ss;
      return currentdate + " " + time;
    },
    // 获取当前是第几季度
    getQuarterByMonth() {
      var today = new Date(); //获取当前时间
      var month = today.getMonth() + 1; //getMonth返回0-11
      //下面是几个if
      if (month >= 1 && month <= 3) {
        return 1;
      } else if (month >= 4 && month <= 6) {
        return 2;
      } else if (month >= 7 && month <= 9) {
        return 3;
      } else {
        return 4;
      }
    },

    // 计算当前日期星座
    getHoroscope(date) {
      let c = [
        "摩羯",
        "水瓶",
        "双鱼",
        "白羊",
        "金牛",
        "双子",
        "巨蟹",
        "狮子",
        "处女",
        "天秤",
        "天蝎",
        "射手",
        "摩羯",
      ];
      date = new Date(date);
      let month = date.getMonth() + 1;
      let day = date.getDate();
      let startMonth = month - (day - 14 < "865778999988".charAt(month));
      return c[startMonth] + "座";
    },
    // 计算指定时间与当前的时间差
    sumAge(data) {
      let dateBegin = new Date(data.replace(/-/g, "/"));
      let dateEnd = new Date(); //获取当前时间
      let dateDiff = dateEnd.getTime() - dateBegin.getTime(); //时间差的毫秒数
      let dayDiff = Math.floor(dateDiff / (24 * 3600 * 1000)); //计算出相差天数
      let leave1 = dateDiff % (24 * 3600 * 1000); //计算天数后剩余的毫秒数
      let hours = Math.floor(leave1 / (3600 * 1000)); //计算出小时数
      //计算相差分钟数
      let leave2 = leave1 % (3600 * 1000); //计算小时数后剩余的毫秒数
      let minutes = Math.floor(leave2 / (60 * 1000)); //计算相差分钟数
      //计算相差秒数
      let leave3 = leave2 % (60 * 1000); //计算分钟数后剩余的毫秒数
      let seconds = Math.round(leave3 / 1000);
      return dayDiff + "天 " + hours + "小时 ";
    },
    // 获取年龄
    getAgeByBirthday(data) {
      let birthday = new Date(data.replace(/-/g, "/"));
      let d = new Date();
      return (
        d.getFullYear() -
        birthday.getFullYear() -
        (d.getMonth() < birthday.getMonth() ||
        (d.getMonth() == birthday.getMonth() &&
          d.getDate() < birthday.getDate())
          ? 1
          : 0)
      );
    },
    // 计算两个日期相差的天数
    getDiffDay(date_1, date_2) {
      // 计算两个日期之间的差值
      let totalDays, diffDate;
      let myDate_1 = Date.parse(date_1);
      let myDate_2 = Date.parse(date_2);
      // 将两个日期都转换为毫秒格式,然后做差
      diffDate = Math.abs(myDate_1 - myDate_2); // 取相差毫秒数的绝对值
      totalDays = Math.floor(diffDate / (1000 * 3600 * 24)); // 向下取整
      return totalDays; // 相差的天数
    },
  },
};
</script>

2023-8-24更新 ↓↓↓

获取指定月份的开始日期

/**
 * @description 月开始时间
 *  @param {Object} year 年
 *  @param {Object} month 月
 */
export function getFirstDayOfMonth(year, month) {
    let data = new Date(year, month - 1, 1);
    return (
        data.getFullYear() +
        "-" +
        (data.getMonth() + 1 > 9 ?
            data.getMonth() + 1 :
            "0" + (data.getMonth() + 1)) +
        "-" +
        (data.getDate() > 9 ? data.getDate() : "0" + data.getDate())
    );
}

获取指定月的结束日期

/**
 * @description 月结束时间
 *  @param {Object} year 年
 *  @param {Object} month 月
 */
export function exportgetLastDayOfMonth(year, month) {
    let data = new Date(year, month, 0);
    return (
        data.getFullYear() +
        "-" +
        (data.getMonth() + 1 > 9 ?
            data.getMonth() + 1 :
            "0" + (data.getMonth() + 1)) +
        "-" +
        (data.getDate() > 9 ? data.getDate() : "0" + data.getDate())
    );
}

获取指定日期是今年的第几周

/**
 * @description 传入日期,返回这一天在今年是第几周
 *  @param {Object} a 年
 *  @param {Object} b 月
 *  @param {Object} c 日
 */
export function getYearWeek(a, b, c) {
    //a为年 b为月 c为日
    /*  
       date1是当前日期  
       date2是当年第一天  
       d是当前日期是今年第多少天  
       用d + 当前年的第一天的周差距的和在除以7就是本年第几周  
   */
    var date1 = new Date(a, parseInt(b) - 1, c),
        date2 = new Date(a, 0, 1),
        d = Math.round((date1.valueOf() - date2.valueOf()) / 86400000);
    return Math.ceil((d + (date2.getDay() + 1 - 1)) / 7);
}

获取指定周的开始结束时间

/**
 * @description 传入日期,返回这一周的开始和结束时间
 *  @param {Object} weekstr 格式:2023-32  这个32是周数
 */
export function week_date(weekstr) {
    let year = weekstr.split('-')[0];
    let weekNo = weekstr.split('-')[1];
    // 此年1号是星期几
    // console.log('调用时传的',year,weekNo);
    let oneday = new Date(year + '-01-01').getDay(); //0-6
    // console.log(oneday);
    // 方便计算,当为星期天时为7
    if (oneday == 0) {
        oneday = 7;
    }

    let one_fistday;
    let one_lastday;
    // 如果1号刚好是星期一
    if (oneday == 1) {
        one_fistday = year + '-01-01';
        one_lastday = year + '-01-07';
    } else {
        let jj = 8 - oneday;
        one_fistday = year - 1 + '-12-' + (31 - oneday + 2 > 9 ? 31 - oneday + 2 : '0' + (31 - oneday + 2));
        one_lastday = year + '-01-' + (jj > 9 ? jj : '0' + jj);
    }

    let fistday;
    let lastday;
    // 如果刚好是第一周
    if (weekNo == 1) {
        fistday = one_fistday;
        lastday = one_lastday;
    } else {
        fistday = addDate(one_lastday, (weekNo - 2) * 7 + 1);
        lastday = addDate(one_lastday, (weekNo - 1) * 7);
    }
    return [fistday, lastday];
}

function addDate(date, days) {
    var d = new Date(date);
    d.setDate(d.getDate() + days);
    var m = d.getMonth() + 1;
    return d.getFullYear() + '-' + (m > 9 ? m : '0' + m) + '-' + (d.getDate() > 9 ? d.getDate() : '0' + d.getDate());
}

获取指定两个日期间隔天数

/**
 * @description 日期间隔:传入两个日期,返回日期间隔天数
 * @param {Object} date_1 开始日期
 * @param {Object} date_1 结束日期
 */
export function dateDiff(date_1, date_2) {
    let totalDays, diffDate
    let myDate_1 = Date.parse(date_1)
    let myDate_2 = Date.parse(date_2)
    // 将两个日期都转换为毫秒格式,然后做差
    diffDate = Math.abs(myDate_1 - myDate_2) // 取相差毫秒数的绝对值
    totalDays = Math.floor(diffDate / (1000 * 3600 * 24)) // 向下取整
    return totalDays // 相差的天数
}

中国标准时间转年月日

/**
 * @description 中国标准时间转年月日
 * @param {Object} time  中国标准时间
 */
export function newDate(time) {
    var date = new Date(time)
    var y = date.getFullYear()
    var m = date.getMonth() + 1
    m = m < 10 ? '0' + m : m
    var d = date.getDate()
    d = d < 10 ? '0' + d : d
    return y + '-' + m + '-' + d
}

中国标准时间转年月日 时分秒

/**
 * @description 中国标准时间转年月日时分秒
 * @param {Object} time  中国标准时间
 */
export function newDate2(time) {
    var date = new Date(time)
    var y = date.getFullYear()
    var m = date.getMonth() + 1
    m = m < 10 ? '0' + m : m
    var d = date.getDate()
    d = d < 10 ? '0' + d : d
    var h = date.getHours();
    var minute = date.getMinutes();
    var miao = date.getSeconds();
    h = h < 10 ? ('0' + h) : h;
    minute = minute < 10 ? ('0' + minute) : minute;
    miao = miao < 10 ? ('0' + miao) : miao;
    return y + '-' + m + '-' + d + ' ' + h + ':' + minute + ':' + miao
}

指定年月日转成中国标准时间

/**
* @description 年月日转中国标准时间
* @param {Object} time  年月日
*/
export function dateTrans(date) {
    let result = new Date(date);
    return result;
}

返回当月天数

currentMonthDays = function () {
    var date = new Date();
    var month = date.getMonth() + 1;
    curDate.setMonth(curMonth + 1);
    var end = curDate.getDate()
    return end
}

时间戳转日期格式

formatDate = function (value) { //10位时间戳转换
    let date = new Date(parseInt(value) * 1000);
    let y = date.getFullYear();
    let m = date.getMonth() + 1;
    m = m < 10 ? "0" + m : m;
    let d = date.getDate();
    d = d < 10 ? "0" + d : d;
    let h = date.getHours();
    h = h < 10 ? "0" + h : h;
    let minute = date.getMinutes();
    let second = date.getSeconds();
    minute = minute < 10 ? "0" + minute : minute;
    second = second < 10 ? "0" + second : second;
    return y + '-' + m + '-' + d;
}

获取今天的年月日时分秒

/**
* @description 获取当前年月日 时分秒
*/
export function getNowDate() {
    var date = new Date();
    var sign2 = ":";
    var year = date.getFullYear() // 年
    var month = date.getMonth() + 1; // 月
    var day = date.getDate(); // 日
    var hour = date.getHours(); // 时
    var minutes = date.getMinutes(); // 分
    var seconds = date.getSeconds() //秒
    var weekArr = ['星期一', '星期二', '星期三', '星期四', '星期五', '星期六', '星期天'];
    var week = weekArr[date.getDay()];
    // 给一位数的数据前面加 “0”
    if (month >= 1 && month <= 9) {
        month = "0" + month;
    }
    if (day >= 0 && day <= 9) {
        day = "0" + day;
    }
    if (hour >= 0 && hour <= 9) {
        hour = "0" + hour;
    }
    if (minutes >= 0 && minutes <= 9) {
        minutes = "0" + minutes;
    }
    if (seconds >= 0 && seconds <= 9) {
        seconds = "0" + seconds;
    }
    return year + "-" + month + "-" + day + " " + hour + sign2 + minutes + sign2 + seconds;
}

时间戳转换成日期格式,年月日时分秒

/**
* @description 时间戳转换成年月日时分秒
*/
export function timestampToTime(timestamp) {
    // 时间戳为10位需*1000,时间戳为13位不需乘1000
    var date = new Date(timestamp * 1000);
    var Y = date.getFullYear() + "-";
    var M =
        (date.getMonth() + 1 < 10
            ? "0" + (date.getMonth() + 1)
            : date.getMonth() + 1) + "-";
    var D = (date.getDate() < 10 ? "0" + date.getDate() : date.getDate()) + " ";
    var h = date.getHours() + ":";
    var m = date.getMinutes() + ":";
    var s = date.getSeconds();
    return Y + M + D + h + m + s;
}

指定日期的前几天或者后几天,参数按顺序:日期,天数(-1代表前一天,1代表后一天,自行增加),日期返回格式

// 获取某天日期的下一天,默认为第二天 默认输出格式为yyyy-mm-dd
            getNextDate(date, day = 1, format = '{y}-{m}-{d}') {
                if (date) {
                    date = date.match(/\d+/g).join('-'); // 格式为2022年09月19日处理
                    const nDate = new Date(date);
                    nDate.setDate(nDate.getDate() + day);

                    const formatObj = {
                        y: nDate.getFullYear(),
                        m: nDate.getMonth() + 1,
                        d: nDate.getDate(),
                    };
                    return format.replace(/{([ymd])+}/g, (result, key) => {
                        const value = formatObj[key];
                        return value.toString().padStart(2, '0');
                    });
                } else {
                    console.log('date格式不正确');
                }
            },

获取今天日期的年月日时分秒

getNowDate() {
                var date = new Date();
                var sign2 = ":";
                var year = date.getFullYear() // 年
                var month = date.getMonth() + 1; // 月
                var day = date.getDate(); // 日
                var hour = date.getHours(); // 时
                var minutes = date.getMinutes(); // 分
                var seconds = date.getSeconds() //秒
                var weekArr = ['星期一', '星期二', '星期三', '星期四', '星期五', '星期六', '星期天'];
                var week = weekArr[date.getDay()];
                // 给一位数的数据前面加 “0”
                if (month >= 1 && month <= 9) {
                    month = "0" + month;
                }
                if (day >= 0 && day <= 9) {
                    day = "0" + day;
                }
                if (hour >= 0 && hour <= 9) {
                    hour = "0" + hour;
                }
                if (minutes >= 0 && minutes <= 9) {
                    minutes = "0" + minutes;
                }
                if (seconds >= 0 && seconds <= 9) {
                    seconds = "0" + seconds;
                }
                return year + "-" + month + "-" + day + " " + hour + sign2 + minutes + sign2 + seconds;
            },

获取两个月份之间的包含开始结束月的所有月份数组

参数传入2023-06,0223-09 返回值长这样:[2023-06 , 2023-07, 2023-08, 2023-09]

month_interval(date1, date2) {
                const startDate = new Date(date1);
                const endDate = new Date(date2);
                const result = [];
                while (startDate <= endDate) {
                    result.push(this.newDate(startDate))//把中国标准时间转成日期格式保存到数组中
                    startDate.setMonth(startDate.getMonth() + 1);//月数加1
                };
                return result;
            },

传入指定日期,获取上一年的日期

//获取指定日期的前一年
function getYearLast(dateStr) {
    // 假设要获取的日期为dateStr,格式为"YYYY-MM-DD"
    let date = new Date(dateStr);
    let lastYear = date.getFullYear() - 1; // 获取前一年的年份
    let newMonth = date.getMonth(); // 新日期的月份
    let newDate; // 新日期的日期
    // 判断原日期的月份是否为2月份
    if (date.getMonth() === 1) { // 2月份
        // 判断前一年是否为闰年
        if (lastYear % 4 === 0 && lastYear % 100 !== 0 || lastYear % 400 === 0) { // 闰年
            newDate = Math.min(date.getDate(), 29); // 新日期的日期最大为29
        } else { // 平年
            newDate = Math.min(date.getDate(), 28); // 新日期的日期最大为28
        }
    } else { // 非2月份
        newDate = date.getDate(); // 新日期的日期为原日期的日期
    }
    let newDateStr = lastYear + "-" + (newMonth + 1) + "-" + newDate; // 格式化日期字符串
    return newDateStr
}

你可能感兴趣的:(功能实现,javascript,前端,vue.js,日期格式,获取日期)