How do I get the current date in Java?
In C# it is DateTime.Now
.
How do I get the current date in Java?
In C# it is DateTime.Now
.
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. :)
import java.util.Date;
Date now = Date();
Note that the Date object is mutable and if you want to do anything sophisticated, use jodatime.
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();
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