Rohit
Rohit

Reputation: 11

How to get the first date and last date of current quarter in java.util.Date when fiscal year starts from August

I need to get the first date of the current quarter as a java.util.Date object and the last date of the current quarter as a java.util.Date object.

I have found methods giving me quarter information, for instance

LocalDate.now().get(IsoFields.QUARTER_OF_YEAR)

but this assumes that Quarter 1 starts from January.

Can someone help me to get the first and last dates assuming that
Q1 = Aug, Sep, Oct
Q2 = Nov, Dec, Jan
Q3 = Feb, Mar, Apr
etc.

Upvotes: 1

Views: 494

Answers (1)

MC Emperor
MC Emperor

Reputation: 22967

Well, the first thing we do is writing a method which adjusts a given date into the start of a quarter. Below is an example which takes the current date and the month of the start of the 'year' (in your case August):

public static LocalDate toStartDateOfQuarter(LocalDate now, Month start) {
    int minusMonths = (start.getValue() + now.getMonthValue() - 1) % 3;
    return now.withDayOfMonth(1).minusMonths(minusMonths);
}

The we could use it like this:

Month startMonth = Month.AUGUST;
LocalDate now = LocalDate.now();
LocalDate startOfQuarter = toStartDateOfQuarter(now, startMonth);
LocalDate endOfQuarter = YearMonth.from(startOfQuarter).plusMonths(2).atEndOfMonth();

This is a different approach, but this abstracts away the implementation of the start-day-of-quarter or end-day-of-quarter implementations.

public class QuarterAdjusterFactory {

    private final Month startOfYear;

    public QuarterAdjusterFactory(Month startOfYear) {
        this.startOfYear = startOfYear;
    }

    private int minusMonths(Temporal temporal) {
        return (startOfYear.getValue() + temporal.get(ChronoField.MONTH_OF_YEAR) - 1) % 3;
    }

    public TemporalAdjuster startOfQuarter() {
        return temporal -> temporal
            .with(ChronoField.DAY_OF_MONTH, 1)
            .minus(minusMonths(temporal), ChronoUnit.MONTHS);
    }

    public TemporalAdjuster endOfQuarter() {
        return temporal -> YearMonth.from(temporal)
            .minus(minusMonths(temporal) - 2, ChronoUnit.MONTHS)
            .atEndOfMonth();
    }
}

Use it with just this:

QuarterAdjusterFactory factory = new QuarterAdjusterFactory(Month.AUGUST);
LocalDate start = date.with(factory.startOfQuarter());
LocalDate end = date.with(factory.endOfQuarter());

Upvotes: 2

Related Questions