Wednesday, May 7, 2014

Using Calendar to find the # of days between 2 Date's

I am pretty sure most of you have done something like this before and it is a very simple solution. The below piece of code is to find the Period between two java.util.Date fields using the Calendar object:

import java.util.Date;
import java.util.Calendar;

public class CalendarTest{

     public static void main(String []args){
        Date fromDate = new Date();
        Date toDate = new Date();
       
        Calendar fromCal = Calendar.getInstance();
        Calendar toCal = Calendar.getInstance();
       
        fromCal.setTime(fromDate);
        toCal.setTime(toDate);
       
        int range = toCal.get(Calendar.DAY_OF_YEAR) - fromCal.get(Calendar.DAY_OF_YEAR);
       
        System.out.println("Range: " + range);
     }
}

The above is how you would have to do in and upto Java 7. However, Java 8 has a brand new Date and Time API and I am going to give it try and see how it looks.

public class Java8TimeTest
{
  public static void main(String[] args)
  {
    LocalDate today = LocalDate.now();
    LocalDate dayInFuture = LocalDate.of(2020, Month.JANUARY, 1);
   
    long dayCount = ChronoUnit.DAYS.between(today, dayInFuture);
    System.out.println("There are " + dayCount + " days left until 2020");
  }
}

Trying out for the first time, the API's are very intuitive and I am loving it. Let upgrade to Java 8 soon!!!

No comments:

Post a Comment