Pick current date from machine

Asked

Viewed 9,610 times

8

I need that when you execute the code it takes the current system date and assign to a Date.

Example:

Date x = new Date(now);

2 answers

8

Just don’t pass any parameter. So:

Date now = new Date();

As can be seen here, this is the same as calling the builder passing the value of System.currentTimeMillis:

Date now = new Date(System.currentTimeMillis());

However, the class java.util.Date may present you with time zone problems. In most cases we don’t want to worry if Java is running on a machine in Brazil or Japan.

So if you’re using Java 8, prefer the new date and time API where the class exists LocalDateTime:

LocalDateTime now = LocalDateTime.now(); 

7


Date x = new Date();

The standard constructor of Date creates the object Date with the date and current time of the system clock, as reported by the operating system.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.