JavaScript 常用方法(2):js获取最近n小时,最近n天,最近n个月,最近n年,未来n天的时间数组,当月、上月、下月所有天数,当月、上月、下月的第一天和最后一天

js获取最近n小时,最近n天,最近n个月,最近n年,未来n天的时间数组,当月、上月、下月所有天数,当月、上月、下月的第一天和最后一天

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

(1)JS时间格式化函数

// Date 对象方法
// getDate()   从 Date 对象返回一个月中的某一天 (1 ~ 31)。
// setDate()   设置 Date 对象中月的某一天 (1 ~ 31)。
// getMonth()  从 Date 对象返回月份 (0 ~ 11)。
// setMonth()  设置 Date 对象中月份 (0 ~ 11)。
// getSeconds() 返回 Date 对象的秒数 (0 ~ 59)。
// getTime()   返回 1970 年 1 月 1 日至今的毫秒数。
// getHours()  返回 Date 对象的小时 (0 ~ 23)。
// setHours()  设置 Date 对象中的小时 (0 ~ 23)。

/**
 * @description 时间格式化函数
 * @param {string} fmt - 时间格式,例如: "yyyy-MM-dd HH:mm:ss"
 * @param {Object} date - 日期对象,例如:new Date()
 * @return {string} 返回格式化后的日期字符串
 **/
function dateFtt(fmt, date) {
  const o = {
    'M+': date.getMonth() + 1, // 月份
    'd+': date.getDate(), // 日
    'H+': date.getHours(), // 小时
    'm+': date.getMinutes(), // 分
    's+': date.getSeconds(), // 秒
    'q+': Math.floor((date.getMonth() + 3) / 3), // 季度
    'S': date.getMilliseconds(), // 毫秒
    'W': ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'][date.getDay()], // 星期
  }
  if (/(y+)/.test(fmt)) { fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length)) }
  for (const k in o) {
    if (new RegExp('(' + k + ')').test(fmt)) { fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? (o[k]) : (('00' + o[k]).substr(('' + o[k]).length))) }
  }
  return fmt
}

(2)JS获取最近n小时时间数组

/**
 * @description 获取最近n(24、36、48、72)小时  时间数组
 * @param {Object} date - 日期对象 例如:new Date()
 * @param {number} [n=24]  - 最近多少个小时, 默认值为:24  例如:24
 * @param {string} [format='yyyy-MM-dd HH:mm:ss'] - 输出时间格式  例如:yyyy-MM-dd HH:mm:ss
 * @param {Object[]} result - 返回时间数组
 **/
function getTheLastHours(date, n = 24, format = 'yyyy-MM-dd HH:mm:ss') {
  let result = [];
  date.setHours(date.getHours());
  for (let i = 0; i < n; i++) {
    date.setHours(date.getHours() - 1);
    result.push(dateFtt(format, date));
  }
  return result.reverse();
}

示例:

let lastHours24 = getTheLastHours(new Date(), 24, 'yyyy-MM-dd HH时');
console.log('获取最近24小时时间数组', lastHours24);
// ['2024-03-25 09时', '2024-03-25 10时', '2024-03-25 11时', '2024-03-25 12时', '2024-03-25 13时', '2024-03-25 14时', '2024-03-25 15时', '2024-03-25 16时', '2024-03-25 17时', '2024-03-25 18时', '2024-03-25 19时', '2024-03-25 20时', '2024-03-25 21时', '2024-03-25 22时', '2024-03-25 23时', '2024-03-26 00时', '2024-03-26 01时', '2024-03-26 02时', '2024-03-26 03时', '2024-03-26 04时', '2024-03-26 05时', '2024-03-26 06时', '2024-03-26 07时', '2024-03-26 08时']

在这里插入图片描述

(3)JS获取最近n天时间数组

/**
  * @description 获取最近n(7、30、60、90)天  时间数组
  * @param {Object} date - 日期对象 例如:new Date()
  * @param {number} [n=30]  - 最近多少天, 默认值为30  例如:30
  * @param {string} [format='yyyy-MM-dd HH:mm:ss'] - 输出时间格式  例如:yyyy-MM-dd HH:mm:ss
  * @return {Object[]} result - 返回时间数组
  **/
function getTheLastDays(date, n = 30, format = 'yyyy-MM-dd HH:mm:ss') {
  let result = [];
  // result.push(dateFtt(format, date));
  for (let i = 0; i < n; i++) {
    date.setDate(date.getDate() - 1);
    result.push(dateFtt(format, date));
  }
  return result.reverse();
}

示例:

let lastDays30 = getTheLastDays(new Date(), 30, 'yyyy-MM-dd');
console.log('获取最近30天的时间数组:', lastDays30);
// ['2024-02-25', '2024-02-26', '2024-02-27', '2024-02-28', '2024-02-29', '2024-03-01', '2024-03-02', '2024-03-03', '2024-03-04', '2024-03-05', '2024-03-06', '2024-03-07', '2024-03-08', '2024-03-09', '2024-03-10', '2024-03-11', '2024-03-12', '2024-03-13', '2024-03-14', '2024-03-15', '2024-03-16', '2024-03-17', '2024-03-18', '2024-03-19', '2024-03-20', '2024-03-21', '2024-03-22', '2024-03-23', '2024-03-24', '2024-03-25']

在这里插入图片描述

(4)JS获取最近n个月时间数组

/**
  * @description 获取最近n(24、36、48、72)个月  时间数组
  * @param {Object} date - 日期对象  例如:new Date()
  * @param {number} [n=12] 最近多少个月  例如:24
  * @param {string} [format='yyyy-MM-dd HH:mm:ss'] 输出时间格式  例如:yyyy-MM-dd HH:mm:ss
  * @return {Object[]} result - 返回时间数组
  **/
function getTheLastMonths(date, n = 12, format = 'yyyy-MM-dd HH:mm:ss') {
  let result = [];
  date.setDate(1);
  date.setMonth(date.getMonth() + 1);  // 获取当前月份,设置月份
  for (let i = 0; i < n; i++) {
    date.setMonth(date.getMonth() - 1);
    result.push(dateFtt(format, date));
  }
  return result.reverse();
}

示例:

let lastMonths12 = getTheLastMonths(new Date(), 12, 'yyyy-MM');
console.log('获取最近12个月的时间数组:', lastMonths12);
// ['2023-04', '2023-05', '2023-06', '2023-07', '2023-08', '2023-09', '2023-10', '2023-11', '2023-12', '2024-01', '2024-02', '2024-03']

在这里插入图片描述

(5)JS获取最近n年时间数组

/**
  * @description 获取最近n(3、5、10、15)年  时间数组
  * @param {Object} date - 日期对象  例如:new Date()
  * @param {number} [n=5] 最近多少年  例如:5
  * @param {string} [format='yyyy-MM-dd HH:mm:ss'] 输出时间格式  例如:yyyy-MM-dd HH:mm:ss
  * @return {Object[]} result - 返回时间数组
  **/
function getTheLastYears(date, n = 5, format = 'yyyy-MM-dd HH:mm:ss') {
  let result = [];
  for (let i = 0; i < n; i++) {
    date.setFullYear(date.getFullYear() - 1);
    result.push(dateFtt(format, date));
  }
  return result.reverse();
}

示例:

let lastYears5 = getTheLastYears(new Date(), 5, 'yyyy');
console.log('获取最近5年的时间数组:', lastYears5);
// ['2019', '2020', '2021', '2022', '2023']

在这里插入图片描述

(6)JS获取未来n天时间数组

/**
  * @description 获取未来n(7、30、60、90)天  时间数组
  * @param {Object} date - 日期对象  例如:new Date()
  * @param {number} [n=7] 未来多少天  例如:30 
  * @param {string} [format='yyyy-MM-dd HH:mm:ss'] 输出时间格式  例如:yyyy-MM-dd HH:mm:ss
  * @return {Object[]} result - 返回时间数组
  **/
function getNextDays(date, n = 7, format = 'yyyy-MM-dd HH:mm:ss') {
  let result = [];
  for (let i = 0; i < n; i++) {
    date.setDate(date.getDate() + 1);
    result.push(dateFtt(format, date));
  }
  return result;
}

示例:

let nextDays7 = getNextDays(new Date(), 7, 'yyyy-MM-dd');
console.log('获取未来7天的时间数组:', nextDays7);
// ['2024-03-27', '2024-03-28', '2024-03-29', '2024-03-30', '2024-03-31', '2024-04-01', '2024-04-02']

在这里插入图片描述

(7)JS 获取本月第一天和最后一天,获取上个月第一天和最后一天,获取下个月第一天和最后一天

    /**
     * JS 获取本月第一天和最后一天,获取上个月第一天和最后一天,获取下个月第一天和最后一天
     * 第三个参数 0和1的区别:
     * 1)0会转换为:第二个参数的最后一天;
     *    如new Date(2024, 1, 0) => 2024年01月31号
     * 2)1会转换为:第二个参数+1的第一天;
     *    如new Date(2024, 1, 1) => 2024年02月01号 
     **/
    // 示例:
    console.log(dateFtt('yyyy-MM-dd', new Date(2024, 1, 0)));  // 2024-01-31
    console.log(dateFtt('yyyy-MM-dd', new Date(2024, 1, 1)));  // 2024-02-01

    let currentDate = new Date();
    console.log('获取本月的第一天和最后一天:');
    console.log(dateFtt('yyyy-MM-dd', new Date(currentDate.getFullYear(), currentDate.getMonth(), 1)));  // 2024-03-01
    console.log(dateFtt('yyyy-MM-dd', new Date(currentDate.getFullYear(), currentDate.getMonth() + 1, 0)));  // 2024-03-31
    console.log('获取上个月的第一天和最后一天:');
    console.log(dateFtt('yyyy-MM-dd', new Date(currentDate.getFullYear(), currentDate.getMonth() - 1, 1)));  // 2024-02-01
    console.log(dateFtt('yyyy-MM-dd', new Date(currentDate.getFullYear(), currentDate.getMonth(), 0)));  // 2024-02-29
    console.log('获取下个月的第一天和最后一天:');
    console.log(dateFtt('yyyy-MM-dd', new Date(currentDate.getFullYear(), currentDate.getMonth() + 1, 1)));  // 2024-04-01
    console.log(dateFtt('yyyy-MM-dd', new Date(currentDate.getFullYear(), currentDate.getMonth() + 2, 0)));  // 2024-04-30

在这里插入图片描述

(8)JS获取某月所有天数数组

<div class="btn_box">
	<div class="btn_one" onClick="switchDate(1)">上个月</div>
    <div class="btn_one" onClick="switchDate(2)">当月</div>
    <div class="btn_one" onClick="switchDate(3)">下个月</div>
</div>
  <style>
    .btn_box {
      display: flex;
    }

    .btn_one {
      background-color: #ccc;
      padding: 2px 10px;
      margin-right: 10px;
      border-radius: 5px;
      cursor: pointer;
    }

    .btn_one:hover {
      background-color: #0078d4;
      color: #fff;
    }
  </style>
let activeBtn = 1;
let currentSelectedDate;
let timeDate;

function switchDate(val) {
  console.log('切换时间按钮', val);
  activeBtn = val;

  let dateList = getDateList();
  console.log('当前点击月份天数', dateList);
}

// 获取某月所有天数数组
function getDateList() {
  let dateList = [];
  let myDate = new Date();
  let year = parseInt(myDate.getFullYear());
  let month = parseInt(myDate.getMonth());
  let year2 = year;
  let month2 = month;

  // 上个月
  if (activeBtn === 1) {
    if (timeDate == null) {
      year2 = year;
      month2 = month + 1;
    } else {
      let str = timeDate;
      let arr = str.substring(0, str.length - 1).split("年");
      year2 = parseInt(arr[0]);
      month2 = parseInt(arr[1]);
    }

    month2 = Math.abs(month2 - 1);

    if (month2 === 0) {
      year2 = year2 - 1;
      month2 = 12;
    }

    month2 = month2 < 10 ? "0" + month2 : month2;
  } else if (activeBtn === 2) { // 当月
    month2 = month2 + 1;
    month2 = month2 < 10 ? "0" + month2 : month2;
  } else if (activeBtn === 3) {
    // 下个月
    if (timeDate == null) {
      year2 = year;
      month2 = month;
    } else {
      let str = timeDate;
      let arr = str.substring(0, str.length - 1).split("年");
      year2 = parseInt(arr[0]);
      month2 = parseInt(arr[1]);
    }

    month2 = Math.abs(month2 + 1);

    if (month2 === 13) {
      year2 = year2 + 1;
      month2 = 1;
    }
    month2 = month2 < 10 ? "0" + month2 : month2;
  }

  console.log(year2, month2);
  let days = new Date(year2, month2, 0).getDate();

  for (let k = 1; k <= days; k++) {
    k = k < 10 ? "0" + k : k;
    let str = year2 + "-" + month2 + "-" + k;
    dateList.push(str);
  }

  let yearMonth = year2 + "-" + month2;
  timeDate = year2 + "年" + month2 + "月";

  console.log('当前日期:', timeDate, '天数:', days);

  return dateList;
}

在这里插入图片描述

(9)JS获取两个日期之间相隔的所有日期

参考:JS - 获取两个日期之间相隔的所有日期

function getDayAll(starDay, endDay) {
        
       var arr = [];
        var dates = [];
    
        // 设置两个日期UTC时间
       var db = new Date(starDay);
       var de = new Date(endDay);
    
        // 获取两个日期GTM时间
       var s = db.getTime() - 24 * 60 * 60 * 1000;
       var d = de.getTime() - 24 * 60 * 60 * 1000;
    
        // 获取到两个日期之间的每一天的毫秒数
       for (var i = s; i <= d;) {
          i = i + 24 * 60 * 60 * 1000;
            arr.push(parseInt(i))
       }
        
        // 获取每一天的时间  YY-MM-DD
        for( var j in arr ){
            var time = new Date(arr[j]);
            var year = time.getFullYear(time);
            var mouth = (time.getMonth() + 1)>=10?(time.getMonth() + 1):('0'+(time.getMonth() + 1));
            var day = time.getDate()>=10?time.getDate():('0'+time.getDate());
            var YYMMDD = year + '-' + mouth + '-' + day;
            dates.push(YYMMDD)
        }
        
        return dates
    }

    var dataAll = getDayAll('2020-01-01','2020-02-01');    
    console.log(dataAll)

在这里插入图片描述

  • 4
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值