How to check if a Date falls in a certain week or Quarter [closed]

I would say do these steps,

1 – figure out first and last day of the week
Get current week start and end date in Java – (MONDAY TO SUNDAY)

2 – check if the date falls in between that range or not
Java: how do I check if a Date is within a certain range?
– if yes, it falls in the week
– if no, it doesn’t

3 – do the same for the quarters, have start and end date, and check if the date falls in between them or not

   //import java.util.*;
   //import java.text.*;

public static void main(String[] args) {

    try {
        SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");

        Date dateToTest = sdf.parse("18/04/2017");

        //lets assume the date source is a variable, hence extract year off of it

        String firstDateInString = "01/04/" +  Integer.toString(getYear(dateToTest));
        String secondDateInString = "01/07/" +  Integer.toString(getYear(dateToTest));
        String thirdDateInString = "01/10/" +  Integer.toString(getYear(dateToTest));

        Date firstDate = sdf.parse(firstDateInString);
        Date secondDate = sdf.parse(secondDateInString);
        Date thirdDate = sdf.parse(thirdDateInString);


        //check if in first quarter
        //if date is before April it has to be first Q
        if (dateToTest.before(firstDate)) {
            System.out.println("First Quarter");
            return;
        }
        //check if in second quarter
        //if date is before August it has to be first Q
        if (dateToTest.before(secondDate)) {
            System.out.println("Second Quarter");
            return;
        }

        //check if in 3rd quarter
        //if date is before August it has to be first Q
        if (dateToTest.before(thirdDate)) {
            System.out.println("third Quarter");
            return;
        }

        //well then the date must be in 4th quarter
        System.out.println("Fourth quarter");
    } catch (Exception err) {
        System.out.println(err);
    }
}

private static int getYear(Date date) {
    Calendar cal = Calendar.getInstance();
    cal.setTime(date);
    return cal.get(Calendar.YEAR);

}

DISCLAIMER: This code is not the optimal method. Please note that here I don’t assume current date or year. Purpose here is to show general strategy only.

Browse More Popular Posts

Leave a Comment