How to get the current date and time

Viewed 405323

How do I get the current date and time in Java?

I am looking for something that is equivalent to DateTime.Now from C#.

10 Answers

Just construct a new Date object without any arguments; this will assign the current date and time to the new object.

import java.util.Date;

Date d = new Date();

In the words of the Javadocs for the zero-argument constructor:

Allocates a Date object and initializes it so that it represents the time at which it was allocated, measured to the nearest millisecond.

Make sure you're using java.util.Date and not java.sql.Date -- the latter doesn't have a zero-arg constructor, and has somewhat different semantics that are the topic of an entirely different conversation. :)

The Java Date and Calendar classes are considered by many to be poorly designed. You should take a look at Joda Time, a library commonly used in lieu of Java's built-in date libraries.

The equivalent of DateTime.Now in Joda Time is:

DateTime dt = new DateTime();

Update

As noted in the comments, the latest versions of Joda Time have a DateTime.now() method, so:

DateTime dt = DateTime.now();
import java.util.Date;   
Date now = new Date();

Note that the Date object is mutable and if you want to do anything sophisticated, use jodatime.

java.lang.System.currentTimeMillis(); will return the datetime since the epoch

If you create a new Date object, by default it will be set to the current time:

import java.util.Date;
Date now = new Date();
Related