w3resource

Java: Create a Date object using the Calendar class


1. Create Date Using Calendar

Write a Java program to create a Date object using the Calendar class.

Sample Solution:

Java Code:

import java.util.*;
public class Exercise1 {
    public static void main(String[] args)
    {
     int year = 2016;
     int month = 0; // January
     int date = 1;

     Calendar cal = Calendar.getInstance();
     // Sets the given calendar field value and the time value
     // (millisecond offset from the Epoch) of this Calendar undefined.
     cal.clear();
     System.out.println();
     cal.set(Calendar.YEAR, year);
     cal.set(Calendar.MONTH, month);
     cal.set(Calendar.DATE, date);

     System.out.println(cal.getTime());
     System.out.println();
	 }
}

Sample Output:

Fri Jan 01 00:00:00 IST 2016

Flowchart:

Flowchart: Java DateTime, Calendar Exercises - Create a Date object using the Calendar class


For more Practice: Solve these Related Problems:

  • Write a Java program to instantiate a Calendar object for a specific locale and convert it to a Date object.
  • Write a Java program to create a Calendar instance, set custom date values, and generate a Date object from it.
  • Write a Java program to create a Date object using Calendar, then adjust its time zone and display the updated date.
  • Write a Java program to construct multiple Date objects from Calendar instances for different locales and compare them.

Go to:


PREV : Java Date, Time and Calendar Exercises
NEXT : Get Calendar Date Info.

Java Code Editor:

Improve this sample solution and post your code through Disqus

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.