Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find next quarter end date given previous quarter end date using Java

I am having quarter end date of last quarter let it be 30-09-20 , the requirement is to find end date of next quarter i.e 31-12-20. I am using below code to do the same but is it giving wrong output in some scenarios. This solution should be correct for all quarters.

String str = "30-09-20";
SimpleDateFormat format = new SimpleDateFormat("dd-MM-yy");
Date date = format.parse(str);
Date newDate = DateUtils.addMonths(date, 3);
System.out.println(newDate);//Dec 30 - It should be 31 Dec
like image 224
Loren Avatar asked Jan 28 '20 10:01

Loren


People also ask

How do you find the start and end date of a quarter?

To get the quarter’s start or end date of a given date, please do as follows: To calculate the start date of a quarter based on a date: Enter this formula: =DATE(YEAR(A2),FLOOR(MONTH(A2)-1,3)+1,1) into a blank cell where you want to locate the result, and drag the fill handle down to the cells which you want to apply this formula, and all the ...

How to get next day and previous day in Java?

Use LocalDate ‘s plusDays () and minusDays () method to get the next day and previous day, by adding and subtracting 1 from today. Use Date class constructor and pass the time in milliseconds. To get the time for yesterday, get the time for today and subtract total milliseconds in a day.

How to calculate first quarter of year in Excel?

Enter this formula: =DATE(YEAR(A2),FLOOR(MONTH(A2)-1,3)+1,1) into a blank cell where you want to locate the result, and drag the fill handle down to the cells which you want to apply this formula, and all the start dates of the quarter by the given dates have been calculated, see screenshot:

How to get time for Yesterday and next date?

To get the time for yesterday, get the time for today and subtract total milliseconds in a day. Similarily, add total milliseconds in a day to get the time for next date. 3. Complete Example to get next and previous date


Video Answer


2 Answers

To answer your question, I think you are looking for this :

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MM-yy");
LocalDate end = LocalDate.parse("30-09-20", formatter)
    .plusMonths(3)                             // add three months to your date
    .with(TemporalAdjusters.lastDayOfMonth()); // with the last day of the month

Note: don't use the legacy Date library, you tagged your question Java-8 which mean you can use java-time API.


Get last day of current quarter

@deHaar have reason, to get the end date of curent quarter, I would suggest to use :

public LocalDate lastDayFromDateQuarter(String date) {
    final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MM-yy");
    LocalDate ld = LocalDate.parse(date, formatter);
    int quarter = ld.get(IsoFields.QUARTER_OF_YEAR); // Get the Quarter, 1, 2, 3, 4
    // Then create a new date with new quarter * 3 and last day of month
    return ld.withMonth(quarter * 3).with(TemporalAdjusters.lastDayOfMonth());
}

Get last day of next quarter

To get the last day of the next quarter, then you just can add three months to your date like so :

public static LocalDate lastDayFromDateQuarter(String date) {
    final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MM-yy");
    LocalDate ld = LocalDate.parse(date, formatter);
    int quarter = ld.get(IsoFields.QUARTER_OF_YEAR);
    return ld.withMonth(quarter * 3)
            .plusMonths(3)
            .with(TemporalAdjusters.lastDayOfMonth());
}
like image 132
YCF_L Avatar answered Sep 19 '22 14:09

YCF_L


tl;dr

Use YearQuarter class from ThreeTen-Extra.

YearQuarter                                       // A class available in the ThreeTen-Extra library.
.from(                                            // Factory method rather than calling `new`. 
    LocalDate.of( 2020 , Month.SEPTEMBER , 30 )   // Returns a `LocalDate` object, represent a date-only value without a time-of-day and without a time zone.
)                                                 // Returns a `YearQuarter` object.
.plusQuarters( 1 )                                // Perform date-math, resulting in a new `YearQuarter` object (per immutable objects pattern). 
.atEndOfQuarter()                                 // Determine the date of last day of this year-quarter.
.toString()                                       // Generate text in standard ISO 8601 format.

2020-12-31

org.threeten.extra.YearQuarter

The ThreeTen-Extra library provides classes that extend the functionality of the java.time classes built into Java 8 and later. One of its classes is YearQuarter to represent a specific quarter in a specific year. The quarters are defined by calendar-year: Jan-Mar, Apr-June, July-Sept, Oct-Dec.

LocalDate localDate = LocalDate.of( 2020 , Month.SEPTEMBER , 30 ) ;
YearQuarter yearQuarter = YearQuarter.from( localDate ) ;

Move to the next quarter by adding one quarter to our current year-quarter.

The java.time and ThreeTen-Extra classes use immutable objects. So rather than alter ("mutate") the original object, when adding we produce a new object.

YearQuarter followingYearQuarter = yearQuarter.plusQuarters( 1 ) ;

Determine the last day of that quarter.

LocalDate lastDateOfFollowingYearQuarter = followingYearQuarter.atEndOfQuarter() ;

About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.

Where to obtain the java.time classes?

  • Java SE 8, Java SE 9, Java SE 10, Java SE 11, and later - Part of the standard Java API with a bundled implementation.
    • Java 9 adds some minor features and fixes.
  • Java SE 6 and Java SE 7
    • Most of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
  • Android
    • Later versions of Android bundle implementations of the java.time classes.
    • For earlier Android (<26), the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

like image 20
Basil Bourque Avatar answered Sep 17 '22 14:09

Basil Bourque