Java Calendar get days and weeks between two date values

Description

Java Calendar get days and weeks between two date values

import java.util.Calendar;
import java.util.Date;
import java.util.concurrent.TimeUnit;

public class Main {

  public static void main(String[] args) {
    Calendar start = Calendar.getInstance();
    Calendar end = Calendar.getInstance();

    // Set the date to 01/01/2010:12:00
    start.set(2010, 0, 1, 12, 0);// ww  w .  jav a 2  s  .  c o m
    Date endDate = end.getTime();
    System.out.println(endDate);

    long mill = Math.abs(start.getTimeInMillis() - endDate.getTime());
    // Convert to hours
    long hours = TimeUnit.MILLISECONDS.toHours(mill);
    // Convert to days
    Long days = TimeUnit.HOURS.toDays(hours);
    String diff = String.format("%d hour(s) %d min(s)",hours,TimeUnit.MILLISECONDS.toMinutes(mill) - TimeUnit.HOURS.toMinutes(hours));
    System.out.println(diff);

    diff = String.format("%d days", days);
    System.out.println(diff);

    // Divide the number of days by seven for the weeks
    int weeks = days.intValue() / 7;
    diff = String.format("%d weeks", weeks);
    System.out.println(diff);
  }
}



PreviousNext

Related