Java new date
In Java, you can create a new Date
object using the following methods:
new Date()
: This creates aDate
object representing the current date and time.Date currentDate = new Date();
new Date(long millis)
: This creates aDate
object representing the date and time specified by the given number of milliseconds since the epoch (January 1, 1970, 00:00:00 GMT).long millis = System.currentTimeMillis(); Date date = new Date(millis);
new Date(String dateStr)
: This creates aDate
object from a string representation of a date and time in the formatyyyy-MM-dd HH:mm:ss
.String dateStr = "2022-07-25 14:30:00"; Date date = new Date(dateStr);
Note that the
Date
class is now considered legacy and has been replaced by theLocalDate
andLocalDateTime
classes in Java 8 and later. If you're using an earlier version of Java, you may want to consider using theSimpleDateFormat
class to parse and format dates.
Here's an example of how to create a LocalDate
object:
LocalDate date = LocalDate.now();
And here's an example of how to create a LocalDateTime
object:
LocalDateTime dateTime = LocalDateTime.now();
In Java 8 and later, you can also use the java.time
package to work with dates and times.