How to get the current date in Java?


You can get the current date 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, using this you can print the current date as shown below −

Example

Live Demo

import java.text.SimpleDateFormat;
import java.text.ParseException;
import java.util.Date;
public class Demo {
   public static void main(String args[])throws ParseException {      
      Date date = new Date();
      SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yy");
       String str = formatter.format(date);
      System.out.print("Current date: "+str);
   }
}

Output

05/11/20

The now() method of LocalDate class

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

Example

Live Demo

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

Output

Current Date: 2020-11-05

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, using this you can print the current date value as shown below −

Example

Live Demo

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.text.ParseException;
import java.util.Calendar;
public class Test {
   public static void main(String[] args) throws ParseException{
      DateFormat formatter = new SimpleDateFormat("dd/MM/yy");
      Calendar obj = Calendar.getInstance();
      String str = formatter.format(obj.getTime());
      System.out.println("Current Date: "+str );
   }
}

Output

Current Date: 05/11/20

The java.sql.Date class

One of the constructor of the java.sql.Date class accepts a long value representing a date and creates a Date object. Therefore to create a Data object you need to pass the return value of the System.currentTimeMillis() method (returns current epoch value) as a parameter of the java.sql.Date constructor.

Example

Live Demo

public class CreateDate {
   public static void main(String[] args) {
      java.sql.Date date=new java.sql.Date(System.currentTimeMillis());
      System.out.println("Current Date: "+date);
   }
}

Output

Current Date: 2020-11-05

Updated on: 06-Sep-2023

35K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements