获取最近n天的时间,今天距离n天前的时间

 

最终格式如下:["2023-08-08 11:45:50", "2023-08-15 11:45:50"]
或
最终格式如下:["2023-08-08", "2023-08-15"]
/**
 * @Event 方法
 * @description: 获取最近num天的时间
 * @param: num: 最近的天数, isDateTime: 是否需要时分秒(默认是)
 * isDateTime 最终格式如下:["2023-08-08 11:45:50", "2023-08-15 11:45:50"]
 * !isDateTime 最终格式如下:["2023-08-08", "2023-08-15"]
 * */
export function getLastNumDay(num, isDateTime=true) {
  const now = new Date();
  const sevenDaysAgo = new Date(now.getTime() - num * 24 * 60 * 60 * 1000);

  const endDate = formatDate(now);
  const startDate = formatDate(sevenDaysAgo);

  // console.log(`起始日期时间:${startDate},结束日期时间:${endDate}`);

  function formatDate(date) {
    const year = date.getFullYear();
    const month = formatNumber(date.getMonth() + 1);
    const day = formatNumber(date.getDate());
    const hours = formatNumber(date.getHours());
    const minutes = formatNumber(date.getMinutes());
    const seconds = formatNumber(date.getSeconds());
    return isDateTime ? `${year}-${month}-${day} ${hours}:${minutes}:${seconds}` : `${year}-${month}-${day}`;
  }

  function formatNumber(num) {
    return num > 9 ? num : `0${num}`;
  }

  return [startDate, endDate];
}

// 使用 

  import { getLastNumDay } from '@/utils/publicFun'

let arr = getLastNumDay(30, false)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值