Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- * calculate difference between dates taking in consideration these points:
- * - 1 year = 360 days
- * - 1 month = 30 days
- * - results must be rounded up with two decimals
- */
- // import java.util.*;
- public static void main(String[] args) throws Exception {
- calculateDate("27/11/2017", "03/02/2020");
- calculateDate("04/12/2017", "17/08/2022");
- calculateDate("08/12/2017", "17/04/2021");
- calculateDate("15/12/2017", "17/10/2019");
- calculateDate("16/12/2017", "17/09/2019");
- calculateDate("16/12/2017", "17/12/2018");
- calculateDate("19/12/2017", "17/04/2018");
- calculateDate("19/12/2017", "17/11/2018");
- calculateDate("20/12/2017", "17/05/2018");
- calculateDate("20/12/2017", "17/04/2018");
- calculateDate("29/12/2017", "17/02/2020");
- }
- private static void calculateDate(String startDateStr, String endDateStr) throws ParseException {
- System.out.println(System.lineSeparator()+"==========START==========");
- Date dateStart = new SimpleDateFormat("dd/MM/yyyy").parse(startDateStr);
- Calendar cal = Calendar.getInstance();
- cal.setTime(dateStart);
- int year1 = cal.get(Calendar.YEAR);
- int month1 = cal.get(Calendar.MONTH) +1;
- int days1 = cal.get(Calendar.DAY_OF_MONTH);
- Date end = new SimpleDateFormat("dd/MM/yyyy").parse(endDateStr);
- cal = Calendar.getInstance();
- cal.setTime(end);
- int year2 = cal.get(Calendar.YEAR);
- int month2 = cal.get(Calendar.MONTH) +1;
- int days2 = cal.get(Calendar.DAY_OF_MONTH);
- double daysTotal = (360*(year2-year1)+30*(month2-month1)+(days2-days1));
- double monthsTotal = daysTotal/30;
- double yearsTotal = daysTotal/360;
- System.out.println("start: "+ dateStart.toString() + " end: "+ end.toString());
- // round to 2 decimals
- System.out.println("days total: " + (Math.round(daysTotal)) +
- " month : "+ (Math.round(monthsTotal)) + " years total: "+ yearsTotal);
- System.out.println("==========END==========");
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement