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..

java.util.Date

Date date=new Date();

java.util.Calendar and java.util.GregorianCalendar

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

java.time.LocaleDateTime

LocalDateTime localDateTime=LocalDateTime.now();

java.time.LocaleDate

LocalDate localDate=LocalDate.now();

java.time.LocaleTime

LocalTime localTime=LocalTime.now();

 

Complete Example

package com.date;

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");
//java.util.Date
Date date=new Date();
System.out.println("java.util.date 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
//java.time.LocalDateTime
DateTimeFormatter dateTimeFormatter=DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss");
LocalDateTime lDateTime=LocalDateTime.now();
System.out.println("java.time.LocalDateTime Current Date and Time :"+ dateTimeFormatter.format(lDateTime));

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

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

	}

}

Output


java.util.date 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
Advertisements

This site uses Akismet to reduce spam. Learn how your comment data is processed.