Java new date

In Java, you can create a new Date object using the following methods:

  1. new Date(): This creates a Date object representing the current date and time.
    Date currentDate = new Date();
  2. new Date(long millis): This creates a Date 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);
  3. new Date(String dateStr): This creates a Date object from a string representation of a date and time in the format yyyy-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 the LocalDate and LocalDateTime classes in Java 8 and later. If you're using an earlier version of Java, you may want to consider using the SimpleDateFormat 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.