Create and set date using Calendar class - Java Date Time

Java examples for Date Time:Calendar

Description

Create and set date using Calendar class

Demo Code

import java.text.SimpleDateFormat;
import java.util.Calendar;

public class Main {

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

    // Set the date to 01/01/2010:12:00
    cal2.set(2010, 0, 1, 12, 0);//  w w w.ja v a  2 s .c o  m

    System.out.println(formatDate(cal1) + " before " + formatDate(cal2) + "? "
        + cal1.before(cal2));
    System.out.println(cal2.compareTo(cal1));
  }
  public static String formatDate(Calendar cal) {
    SimpleDateFormat simpleFormatter = new SimpleDateFormat(
        "MMM dd yyyy hh:mm:ss aaa");
    return simpleFormatter.format(cal.getTime());
  }
}

Result


Related Tutorials