Date in Java Example

Date in Java Example

In Java we can use java.util.Date package or java.util.Calendar to work with Date and time. Let us see some simple examples.

1) java.util.Date

  • Get current Date

    Date date = new Date();
    System.out.println(date);
    Output
    Sat May 14 16:21:23 IST 2016
  • Convert String to date

    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd/MM/yyyy");
    String strDate = "12/05/2016";
    Date date = simpleDateFormat.parse(strDate);
    System.out.println(date);
    Output
    Thu May 12 00:00:00 IST 2016
  • Date formatting using date formatter

    Date date = new Date();
    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd/MM/yyyy");
    System.out.println(simpleDateFormat.format(date));
    Output
    14/05/2016
  • Get current date time

    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss");
    Date date = new Date();
    System.out.println(simpleDateFormat.format(date));
    Output
    14/05/2016 04:42:16

2) java.util.Calendar

  • Get current Date

    Calendar calendar = Calendar.getInstance();
    Date date = calendar.getTime();
    System.out.println(date);
    Output
    Sat May 14 22:21:06 IST 2016
  • Convert String to Calendar

    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd/MM/yyyy");
    String strDate = "12/05/2016";
    Date date = simpleDateFormat.parse(strDate);
    Calendar calendar = Calendar.getInstance();
    calendar.setTime(date);
    System.out.println(date);
    Output
    Thu May 12 00:00:00 IST 2016
  • Get current date time

    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss");
    Calendar calendar = Calendar.getInstance();
    Date date = calendar.getTime();
    System.out.println(simpleDateFormat.format(date));
    Output
    14/05/2016 10:26:39
  • Add and subtract from date

    Calendar calendar = Calendar.getInstance();
    System.out.println(calendar.getTime());
    		
    //Increment month by 1
    calendar.add(Calendar.MONTH, 1);
    System.out.println(calendar.getTime());
    		
    //Decrement month by 1
    calendar.add(Calendar.MONTH, -1);
    System.out.println(calendar.getTime());
    		
    //Increment day of month by 5
    calendar.add(Calendar.DAY_OF_MONTH, 5);
    System.out.println(calendar.getTime());
    		
    //Decrement day of month by 10
    calendar.add(Calendar.DAY_OF_MONTH, -10);
    System.out.println(calendar.getTime());
    Output
    Sat May 14 22:27:26 IST 2016
    Tue Jun 14 22:27:26 IST 2016
    Sat May 14 22:27:26 IST 2016
    Thu May 19 22:27:26 IST 2016
    Mon May 09 22:27:26 IST 2016

Leave a Reply

Your email address will not be published. Required fields are marked *