How to get Current Date and Time in Java

Filed Under: Java

Java provides two classes to get current date and time – Date and Calendar.

Get Current Date in Java

Here is the simple program showing how we can use these classes to get the current date and time in Java.

package com.journaldev.util;

import java.util.Calendar;
import java.util.Date;

public class DateAndTimeUtil {

	public static void main(String[] args) {
		//Get current date using Date
		Date date = new Date();
		System.out.println("Current date using Date = "+date.toString());

		//Get current date using Calendar
		Calendar cal = Calendar.getInstance();
		System.out.println("Current date using Calendar = "+cal.getTime());

		//Get current time in milliseconds
		System.out.println("Current time in milliseconds using Date = "+date.getTime());
		System.out.println("Current time in milliseconds using Calendar = "+cal.getTimeInMillis());


Output of the above program is:

Current date using Date = Thu Nov 15 13:51:03 PST 2012
Current date using Calendar = Thu Nov 15 13:51:03 PST 2012
Current time in milliseconds using Date = 1353016263692
Current time in milliseconds using Calendar = 1353016263711

Few points to note while getting the current date in java:

  • Calendar.getInstance() is more expensive method, so use it only when you need Calendar object. Else use Date object.
  • The number of milliseconds is the number of milliseconds since January 1, 1970, 00:00:00 GMT.
  • Notice the difference between milliseconds in Calendar and Date object, it’s because of the time taken for java program to create Date and Calendar object. Date object is created first, hence it’s milliseconds value is lower.
  • You can use SimpleDateFormat class to format the date in different ways.

Update: If you are working on Java 8, then you should consider using new Date Time API. For more details, please read Java Date Time API Tutorial.

Leave a Reply

Your email address will not be published. Required fields are marked *

Generic selectors
Exact matches only
Search in title
Search in content