Please disable adblock to view this page.

← Go home

Date and Time in Java


April 30, 2017
Published By : Pratik Kataria
Categorised in:

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();

		GregorianCalendar gc = new GregorianCalendar(2010, 5, 15);
		gc.add(GregorianCalendar.DATE, 1);

		Date date1 = gc.getTime();

		DateFormat df = DateFormat.getDateInstance(DateFormat.FULL);

		LocalDateTime ldt =;

		LocalDate ld = LocalDate.of(2010, 5, 15);

		DateTimeFormatter dtf = DateTimeFormatter.ofPattern("M/d/yyyy");



  • 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


  • 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

Pratik Kataria is currently learning Springboot and Hibernate.
Technologies known and worked on: C/C++, Java, Python, JavaScript, HTML, CSS, WordPress, Angular, Ionic, MongoDB, SQL and Android.
Softwares known and worked on: Adobe Photoshop, Adobe Illustrator and Adobe After Effects.