How to get the current date and time in Java?

JavaServer Side ProgrammingProgramming

You can get the current date and time in Java in various ways. Following are some of them −

The constructor of Date class

The no-arg constructor of the java.util.Date class returns the Date object representing the current date and time.

Example

Live Demo

import java.util.Date;
public class CreateDate {
   public static void main(String args[]) {      
      Date date = new Date();
      System.out.print(date);
   }
}

Output

Thu Nov 05 20:04:57 IST 2020

The now() method of LocalDateTime class

The now() method of the LocaldateTime class returns the Date object representing the current time.

Example

Live Demo

import java.time.LocalDate;
import java.time.LocalDateTime;
public class CreateDateTime {
   public static void main(String args[]) {  
      LocalDateTime date = LocalDateTime.now();
      System.out.println("Current Date and Time: "+date);
   }
}

Output

Current Date and Time: 2020-11-05T21:49:11.507

The getInstance() method of the calendar class

The getInstance() (without arguments) method of the this class returns the Calendar object representing the current date and time.

Example

Live Demo

import java.util.Calendar;
import java.util.Date;
public class CreateDateTime {
   public static void main(String[] args) {
      Calendar obj = Calendar.getInstance();
      Date date = obj.getTime();
      System.out.println("Current Date and time: "+date);
   }
}

Output

Current Date and time: Thu Nov 05 21:46:19 IST 2020

The java.time.Clock class

You can also get the current date ant time value using the java.time.Clock class as shown below −

Example

Live Demo

import java.time.Clock;
public class CreateDateTime {
   public static void main(String args[]) {
      Clock obj = Clock.systemUTC();
      System.out.println("Current date time: "+obj.instant());
   }
}

Output

Current date time: 2020-11-05T16:33:06.155Z
raja
Published on 05-Feb-2021 10:45:15
Advertisements