Typescript获取季度末日期

该代码示例展示了如何利用date-fns库从给定日期开始计算连续8个季度末的日期。首先,定义了一个函数getQuarterEndDate来获取给定日期所在季度的最后一天,然后getNextQuarterEndDates函数用于生成指定数量的后续季度结束日期。最后,提供了一个例子,将2023年7月5日作为输入,输出了接下来8个季度末的日期。
摘要由CSDN通过智能技术生成

根据输入日期计算从当前季度末开始的连续8个季度的季度末日期。

import { addMonths, differenceInDays, endOfMonth } from "date-fns";

// Get the last day of the quarter for a given date
const getQuarterEndDate = (date: Date): Date => {
  const year = date.getFullYear();
  const month = date.getMonth();
  const quarterMonth = Math.floor(month / 3) * 3 + 2; // Calculate the last month of the current quarter
  return endOfMonth(new Date(year, quarterMonth, 1));
};

// Calculate the quarter end dates starting from the current quarter end for a specified number of quarters
const getNextQuarterEndDates = (startDate: Date, count: number): Date[] => {
  const nextQuarterEndDates: Date[] = [];
  let currentQuarterEnd = getQuarterEndDate(startDate);

  for (let i = 0; i < count; i++) {
    if (differenceInDays(startDate, currentQuarterEnd) === 0) {
      count++; // If the start date and current quarter end date are the same, increment the count to include one more quarter
    } else {
      nextQuarterEndDates.push(currentQuarterEnd); // Add the current quarter end date to the result array
    }
    const nextQuarterStart = addMonths(currentQuarterEnd, 1); // Calculate the start date of the next quarter
    currentQuarterEnd = getQuarterEndDate(nextQuarterStart); // Calculate the end date of the next quarter and update it as the current quarter end date
  }

  return nextQuarterEndDates;
};

// Example usage
const inputDate = new Date("2023-07-05");
const nextQuarterEndDates = getNextQuarterEndDates(inputDate, 8);

const formattedDates = nextQuarterEndDates.map((date) =>
  date.toISOString().substring(0, 10)
);
console.log(formattedDates);

新手练习,请大神们指教。 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值