tags:

views:

1776

answers:

6

How do I get the current date in Java?

In C# it is DateTime.Now.

+14  A: 

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

delfuego
Also note that GregorianCalendar and many similar objects work the same way. So whatever type of date/calendar object you are working with, the zero-argument constructor usually initializes the object to the current date/time.
Peter Di Cecco
+2  A: 
import java.util.Date;   
Date now = Date();

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

Chandra Patni
+2  A: 

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();
parkerfath
+1  A: 

I prefer using the Calendar object.

Calendar now = GregorainCalendar.getInstance()

I find it much easier to work with. You can also get a Date object from the Calendar.

http://java.sun.com/javase/6/docs/api/java/util/GregorianCalendar.html

ralphL
A: 

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();
cdmckay
A: 

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