Sunday, March 1, 2015

What is the Equivalent of C#'s DateTime.Now in Java?

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.

NOTE: Make sure you're using java.util.Date and not java.sql.Date
java.sql.Date doesn't have a zero-arg constructor, and it has somewhat different semantics

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.

The Calendar class should be used to convert between dates and time fields and the DateFormat class should be used to format and parse date strings.

Please consider new Java8 APIs - LocalDateTime.now() and ZonedDateTime.now()
More info can be found at http://stackoverflow.com/questions/2010284/equivalent-of-cs-datetime-now-in-java?rq=1
and
http://stackoverflow.com/questions/5175728/how-to-get-the-current-date-time-in-java/26225884#26225884