Date and Time in Java

Understanding through code

import java.text.DateFormat;  import java.time.LocalDateTime;  import java.time.LocalDate;  import java.time.format.DateTimeFormatter;  import java.util.Date;  import java.util.GregorianCalendar;    public class DateTime {  	public static void main( String[] args ){    		Date date = new Date();  		System.out.println(date);    		GregorianCalendar gc = new GregorianCalendar(2010, 5, 15);  		gc.add(GregorianCalendar.DATE, 1);    		Date date1 = gc.getTime();  		System.out.println(date1);    		DateFormat df = DateFormat.getDateInstance(DateFormat.FULL);  		System.out.println(df.format(date1));    		LocalDateTime ldt = LocalDateTime.now();  		System.out.println(ldt);    		LocalDate ld = LocalDate.of(2010, 5, 15);  		System.out.println(ld);    		DateTimeFormatter dtf = DateTimeFormatter.ofPattern("M/d/yyyy");  		System.out.println(dtf.format(ld));    	}  }

Output

  • Mon May 01 00:47:49 IST 2017
  • Wed Jun 16 00:00:00 IST 2010
  • Wednesday, 16 June, 2010
  • 2017-05-01T00:47:50.722
  • 2010-05-15
  • 5/15/2010

Notes

  • Date API is the first API for date and is minimalist API.
  • GregorianCalendar is used for showing specific date.
  • Notice that we get June instead of ‘May’ since we passed 5. It’s index which starts from 0 representing January.
  • gc.add() adds a day.
  • DateFormat is for formatting the date in a readable manner.
  • Java Version 8:
    • LocalDateTime  (equivalent to old Date. Imports through java.time instead of java.util)
    • LocalDateTime gives time in format that is mostly used in databases
    • LocalDate starts numbering of months from 1. So we get 2010-05-15
    • DateTimeFormatter is equivalent to DateFormat in old API