Create a Date object using the Calendar class in Java

Java 8Object Oriented ProgrammingProgramming

For using Calendar class, import the following package.

import java.util.Calendar;

Now, let us create an object of Calendar class.

Calendar calendar = Calendar.getInstance();

Set the date, month and year.

calendar.set(Calendar.YEAR, 2018);
calendar.set(Calendar.MONTH, 11);
calendar.set(Calendar.DATE, 18);

Create a Date object using Calendar class.

java.util.Date dt = calendar.getTime();

The following is an example.

Example

 Live Demo

import java.util.Calendar;
public class Demo {
   public static void main(String[] args) {
      Calendar calendar = Calendar.getInstance();
      // Set year, month and date
      calendar.set(Calendar.YEAR, 2018);
      calendar.set(Calendar.MONTH, 11);
      calendar.set(Calendar.DATE, 18);
      // util date object
      java.util.Date dt = calendar.getTime();
      System.out.println("Date: "+dt);
   }
}

Output

Date: Tue Dec 18 08:29:51 UTC 2018
raja
Published on 17-Dec-2018 09:56:18
Advertisements