How do I get the current date and time in Java?
I am looking for something that is equivalent to DateTime.Now
from C#.
today() method to get the current local date. By the way, date. today() returns a date object, which is assigned to the today variable in the above program. Now, you can use the strftime() method to create a string representing date in different formats.
Calendar Date currentTime = Calendar. getInstance(). getTime();
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. :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With