Reputation: 815
My requirement is simple, I need to show newsletters for last 3 quarters in the screen.
For this I'll have to set the news letter pdf links in session.
So if the user logs in on Feb 2013, he should see 3 links namely
'Newsletter Q1 2013'
'Newsletter Q4 2012'
'Newsletter Q3 2012'
Here is the code so far,
String newsLetter1 = null;
String newsLetter2 = null;
String newsLetter3 = null;
Date date = new Date();
Calendar cal = Calendar.getInstance(Locale.US);
cal.setTime(date);
int month = cal.get(Calendar.MONTH);
int quarter = (month / 3) + 1;
//Do something here to populate newsLetter1, newsLetter2 , newsLetter3
variables based on current date
session.setAttribute("newsLetter1", "Newsletter "+newsLetter1 );
session.setAttribute("newsLetter2", "Newsletter "+newsLetter2);
session.setAttribute("newsLetter3", "Newsletter "+newsLetter3);
I've given it a good thought, but couldn't think of any possible solutions. Please help.
Upvotes: 0
Views: 6354
Reputation: 35557
You can find quarter as follows
Calendar cal=Calendar.getInstance();
int month = cal.get(Calendar.MONTH);
int quarter=0;
if(month<5){
quarter=1;
// news letter belongs to quarter 1
}else if(month<9){
quarter=2;
// news letter belongs to quarter 2
}else {
quarter=3;
// news letter belongs to quarter 3
}
If you want to year with quarter use following
Calendar cal=Calendar.getInstance();
int month = cal.get(Calendar.MONTH);
int year =cal.get(Calendar.YEAR);
if(month<5){
System.out.println(year+" "+"quarter "+1);
}else if(month<9){
System.out.println(year+" "+"quarter "+2);
}else {
System.out.println(year+" "+"quarter "+3);
}
Upvotes: 1
Reputation: 136012
I would do it like this
Calendar cal = Calendar.getInstance();
int month = cal.get(Calendar.MONTH);
int q1 = (month / 3) + 1;
int q2 = q1 == 1 ? 4 : q1 - 1;
int q3 = q2 == 1 ? 4 : q2 - 1;
session.setAttribute("newsLetter1", "Newsletter " + q1);
session.setAttribute("newsLetter2", "Newsletter " + q2);
session.setAttribute("newsLetter3", "Newsletter " + q3);
notes
1) Locale is not relevant in this case
2) cal.setTime(date) is not needed, Calendar.getInstance already returns an instance based on the current time
Upvotes: 0
Reputation: 1217
In every iteration you can sub 3 monthes from current date and calculate quarter by the formula you already have.
int newsLetters = 3;
final Calendar cal = Calendar.getInstance(Locale.US);
for (int i = 0; i < newsLetters; i++) {
cal.add(Calendar.MONTH, -3);
int quarter = (cal.get(Calendar.MONTH) / 3) + 1;
System.out.println("Newsletter Q" + quarter + " " + cal.get(Calendar.YEAR));
}
The output:
Newsletter Q2 2013
Newsletter Q1 2013
Newsletter Q4 2012
Upvotes: 2