Thursday , November 21 2024

How to get current date time in java

Java provides the Date class available in java.util package, this class encapsulates the current date and time.You can also use Calendar class to get current date and time.

Getting Current Date & Time

This is very easy to get current date and time in Java. You can use a simple Date object with toString() method or Calendar class to print current date and time.
And, later use SimpleDateFormat class to convert the date into a user friendly format.



1. Uisng Date class

DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Date date = new Date();
System.out.println(dateFormat.format(date)); //2014/08/06 15:59:48

2. Using Calendar class

DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Calendar cal = Calendar.getInstance();
System.out.println(dateFormat.format(cal.getTime())); //2014/08/06 16:00:22

A full example to show you how to use Date() and Calender() classes to get and display the current date time.

package com.w2class;

import java.util.Date;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;

public class GetCurrentDateTime {
  public static void main(String[] args) {

	   DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
	   //get current date time with Date()
	   Date date = new Date();
	   System.out.println(dateFormat.format(date));
	  
	   //get current date time with Calendar()
	   Calendar cal = Calendar.getInstance();
	   System.out.println(dateFormat.format(cal.getTime()));

  }
}

Output

2016/06/15 14:04:24
2016/066/15 14:04:24




About admin

Check Also

Arrays in java

The array is a data structure which stores a fixed-size sequential collection of elements of …

Leave a Reply