thorax232

Java - Date Arithmetic

Dec 12th, 2013
170
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.38 KB | None | 0 0
  1. // Copied from http://www.javaroots.com/2013/12/date-airthmetics-java.html
  2.  
  3. package com.test;
  4.  
  5. import java.text.ParseException;
  6. import java.text.SimpleDateFormat;
  7. import java.util.Calendar;
  8. import java.util.Date;
  9.  
  10.  
  11. public class DateTest
  12. {
  13.     public static void main(String[] args) throws ParseException
  14.  {
  15.  
  16.      SimpleDateFormat fmt = new SimpleDateFormat("MM/dd/yy");
  17.      Date from = fmt.parse("01/10/12");
  18.      Date to = fmt.parse("04/30/12");
  19.      
  20.      Calendar fromCal = Calendar.getInstance();
  21.      fromCal.setTime(from);
  22.      int fromYear = fromCal.get(Calendar.YEAR);
  23.      Calendar toCal = Calendar.getInstance();
  24.      toCal.setTime(to);
  25.      int toYear = toCal.get(Calendar.YEAR);
  26.      
  27.      int diff = toYear - fromYear ;
  28.      
  29.      for(int i =0 ; i;ltdiff ; i++)
  30.      {
  31.       Calendar calendarEnd=Calendar.getInstance();
  32.          calendarEnd.set(Calendar.YEAR,fromYear);
  33.          calendarEnd.set(Calendar.MONTH,11);
  34.          calendarEnd.set(Calendar.DAY_OF_MONTH,31);
  35.          
  36.          Date calendarEndDate =calendarEnd.getTime();
  37.          
  38.          System.out.println("From "+ fmt.format(from)+" To " +fmt.format(calendarEndDate));
  39.          
  40.          calendarEnd.add(Calendar.DATE,1);
  41.          from = calendarEnd.getTime();
  42.          fromYear++;
  43.      }
  44.      
  45.       System.out.println("From "+ fmt.format(from)+" To " +fmt.format(to));
  46.      
  47.  }
  48. }
Advertisement
Add Comment
Please, Sign In to add comment