Java - get differences between given fortnight and current fortnight
For example:
Data Given :- Year-2010, Month-2, Fortnight-1
- Curre开发者_开发问答nt date
How do I get the difference in terms of number of fortnights between the two given dates?
This is what I figured out and its working fine...
Calendar c= Calendar.getInstance();
int year = 2011;
int month = 6;
int fortnight = 1;
int noofmonths=(c.get(Calendar.YEAR)-year)*12;
noofmonths=(noofmonths+((12-(month-1)+(c.get(Calendar.MONTH)-12)))-1)*2;
int nooffortnights=noofmonths+((2-(fortnight-1)+((c.get(Calendar.DAY_OF_MONTH)<15?1:2)-2)))-1;
System.out.println("nooffortnights : "+nooffortnights); //outputs 5
This depends on your definition of fortnights. If we are literal minded then a fortnight is defined as 14 days, so compute the number of days and divide by 14, job done.
I suspect that in your case we are actually using a special business calendar, where fortnights are a subdivision of quarters and hence there are some special cases - a year doesn't exactly divide into fortnights and perhaps the business year does not start on Jan 1st? So somewhere there will be a definitive list of the dates of the start of each fortnight in a year.
Let's suppose that the fortnight definitions have
17th Nov - 1st Dec
2nd Dec - 15th Dec
16th Dec - 31st Dec (note this is 15 days long)
Now what's the definition on how many fortnights from 17th Nov to 16th Dec? I guess 2. From 19th Nov to 16th Dec? I have no idea what answer you would expect.
So first, get really clear what the business requirements are. I'd be surprised is you will find off-the-shelf date packages that understand fortnights, but even if you do you need to check very carefully that they give the answers you need.
Assuming you want to do this without any 3rd Party libraries
Make 2 Calendar
Objects (both with the given dates).
Calendar c1 = Calendar.getInstance(),c2 = Calendar.getInstance();
c1.add(Calendar.MONTH, 2);
int fortnights = (int)((c1.getTimeInMillis() - c2.getTimeInMillis()) / (14L * 24 * 60 * 60 * 1000));
System.out.println(fortnights); //output should be 4
Note, it's a rough approximation.
精彩评论