Get the seconds difference in Java

Description

The following code shows how to get the seconds difference.

Example


//from ww  w.j a  v  a2s.c  o  m
import java.util.Calendar;
import java.util.Date;

public class Main {
  /**
   * Get the seconds difference
   */
  public final static long SECOND_MILLIS = 1000;

  public static int secondsDiff(Date earlierDate, Date laterDate) {
    if (earlierDate == null || laterDate == null)
      return 0;

    return (int) ((laterDate.getTime() / SECOND_MILLIS) - (earlierDate
        .getTime() / SECOND_MILLIS));
  }

  public static void main(String[] argv) {
    Date date1 = Calendar.getInstance().getTime();
    Calendar cal = Calendar.getInstance();
    cal.set(2010, 10, 10);
    Date date2 = cal.getTime();
    System.out.println(secondsDiff(date1, date2));
  }

}

The code above generates the following result.





















Home »
  Java Tutorial »
    Date »




Date Get
Date Set
Date Format
Date Compare
Date Convert
Date Calculation
Date Parse
Timezone