I am trying to get the quarter in the year using calender class in Java. I am getting current date as below and use WEEK_OF_YEAR variable to get the week as below but below output is not making much sense to me as this week is not 3rd week in this year.
Calendar cal = Calendar.getInstance();
System.out.println(dateFormat.format(cal.getTime()));
System.out.println("week of year: "+cal.WEEK_OF_YEAR);
output: 2014/02/17
week of year: 3
What i wanted to do is, i want to have below quarter (Currently Quarter1 is running and next Quarter is Quarter2) as result and use this on my application.
Quarter1 is from Week 1 to Week 12.
Quarter2 is from Week 13 to Week 24.
Quarter3 is from Week 25 to Week 37.
Quarter4 is from Week 38 to the end of the year.
Please help me with this and let me know how do i find out Quarters as mentioned above.
Calendar.WEEK_OF_YEAR
is a constant. You wanted cal.get(Calendar.WEEK_OF_YEAR)
.
However, you should note that "week of year" is not as simple as you might expect, as a concept. For example, it can be 53 on January 1st, which belongs to the previous week-year in some years. Are you happy for the first quarter of a year to start later than January 1st?
(Unless you really need to use a week-year/week-of-week-year/day-of-week representation for business purposes, year/month/day is much easier to get your head around.)
If you do need to translate the week-of-year into a quarter after reading those caveats, you can just use:
public static int getQuarter(Calendar calendar) {
int weekOfYear = calendar.get(Calendar.WEEK_OF_YEAR);
return weekOfYear < 13 ? 1
: weekOfYear < 25 ? 2
: weekOfYear < 38 ? 3
: 4;
}
See more on this question at Stackoverflow