Advertisement
dwhitzzz

calculate difference dates 360 days years - 30 day month

Feb 18th, 2020
206
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.97 KB | None | 0 0
  1. /*
  2. * calculate difference between dates taking in consideration these points:
  3. * - 1 year = 360 days
  4. * - 1 month = 30 days
  5. * - results must be rounded up with two decimals
  6. */
  7.  
  8. // import java.util.*;
  9. public static void main(String[] args) throws Exception {
  10.  
  11.     calculateDate("27/11/2017", "03/02/2020");
  12.     calculateDate("04/12/2017", "17/08/2022");
  13.     calculateDate("08/12/2017", "17/04/2021");
  14.     calculateDate("15/12/2017", "17/10/2019");
  15.     calculateDate("16/12/2017", "17/09/2019");
  16.     calculateDate("16/12/2017", "17/12/2018");
  17.     calculateDate("19/12/2017", "17/04/2018");
  18.     calculateDate("19/12/2017", "17/11/2018");
  19.     calculateDate("20/12/2017", "17/05/2018");
  20.     calculateDate("20/12/2017", "17/04/2018");
  21.     calculateDate("29/12/2017", "17/02/2020");
  22. }
  23.  
  24. private static void calculateDate(String startDateStr, String endDateStr) throws ParseException {
  25.     System.out.println(System.lineSeparator()+"==========START==========");
  26.     Date dateStart = new SimpleDateFormat("dd/MM/yyyy").parse(startDateStr);
  27.     Calendar cal = Calendar.getInstance();
  28.     cal.setTime(dateStart);
  29.     int year1 = cal.get(Calendar.YEAR);
  30.     int month1 = cal.get(Calendar.MONTH) +1;
  31.     int days1 = cal.get(Calendar.DAY_OF_MONTH);
  32.  
  33.     Date end = new SimpleDateFormat("dd/MM/yyyy").parse(endDateStr);
  34.     cal = Calendar.getInstance();
  35.     cal.setTime(end);
  36.     int year2 = cal.get(Calendar.YEAR);
  37.     int month2 = cal.get(Calendar.MONTH) +1;
  38.     int days2 = cal.get(Calendar.DAY_OF_MONTH);
  39.  
  40.  
  41.     double daysTotal =  (360*(year2-year1)+30*(month2-month1)+(days2-days1));
  42.     double monthsTotal = daysTotal/30;
  43.     double yearsTotal = daysTotal/360;
  44.  
  45.     System.out.println("start: "+ dateStart.toString() + " end: "+  end.toString());
  46.     // round to 2 decimals
  47.     System.out.println("days total: " + (Math.round(daysTotal)) +
  48.              " month : "+ (Math.round(monthsTotal)) + " years total: "+ yearsTotal);
  49.     System.out.println("==========END==========");
  50. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement