Java : How to get current date time?

In below example you will learn ways to get current date and time from Legacy Java Date and Calendar APIs and also from Java 8 LocalDateTime, LocalDate and LocalTime..


Date date=new Date();

java.util.Calendar and java.util.GregorianCalendar

Calendar calendar=Calendar.getInstance();
Calendar gCalnedar=GregorianCalendar.getInstance();








Complete Example


import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;

public class CurrentDateandTimeExample {

public static void main(String[] args) {

SimpleDateFormat dateTimeFormat=new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Date date=new Date();
System.out.println(" Current Date and Time :"+ dateTimeFormat.format(date));

//java.util.Calendar and java.util.GregorianCalendar
Calendar calendar=Calendar.getInstance();
System.out.println("java.util.Calendar Current Date and Time :"+ dateTimeFormat.format(calendar.getTime()));
Calendar gCalendar=GregorianCalendar.getInstance();
System.out.println("java.util.GregorianCalendar Current Date and Time :"+ dateTimeFormat.format(gCalendar.getTime()));

//Java 8
DateTimeFormatter dateTimeFormatter=DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss");
System.out.println("java.time.LocalDateTime Current Date and Time :"+ dateTimeFormatter.format(lDateTime));

DateTimeFormatter dateFormatter=DateTimeFormatter.ofPattern("yyyy/MM/dd");
System.out.println("java.time.LocalDate Current :"+ dateFormatter.format(lDate));

DateTimeFormatter timeFormatter=DateTimeFormatter.ofPattern("HH:mm:ss");
System.out.println("java.time.LocalTime Current Time :"+ timeFormatter.format(lTime));



Output Current Date and Time :2018/08/03 12:12:26
java.util.Calendar Current Date and Time :2018/08/03 12:12:26
java.util.GregorianCalendar Current Date and Time :2018/08/03 12:12:26
java.time.LocalDateTime Current Date and Time :2018/08/03 12:12:26
java.time.LocalDate Current :2018/08/03
java.time.LocalTime Current Time :12:12:26

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s