java.util.Calendar setTime(Date date)

Description :

This java tutorial shows how to use the setTime(Date date) method of Calendar class of java.util package. This method Sets this Calendar’s time with the given Date.

Method Syntax :

public final void setTime(Date date)

Parameter Input :

 

DataType Parameter Description
Date date a given Date

 

Method Returns :

This method returns void.

Compatibility Version :

Requires Java 1.1 and up

Exception :

N/A

Discussion :

The Calender setTime(Date date) is used to set the time that we want to the Calendar object. However, it is preferably practical to use the set method of Calendar class. Why is it so? This method accepts a Date method argument which is already deprecated.

Java Code Example :

This java example source code demonstrates the use of setTime(Date date) method of Calendar class. Initially the example code just prints the current time and then we set a new Date by calling setTime.

package com.javatutorialhq.java.examples;

import java.util.Calendar; import java.util.Date;

/* * This example source code demonstrates the use of * setTime() method of Calendar class */

public class CalendarSetTimeExample {

@SuppressWarnings("deprecation") public static void main(String

[] args) throws InterruptedException {

Calendar cal = Calendar.getInstance(); // Printing the current time System.out.println("Current time:"+cal.getTime());

// set a new Date cal.setTime(new Date(2015, 3, 17));

// Printing the new time System.out.println("New Time:"+cal.getTime());

}

}

Sample Output :

Running the setTime(Date date) method example source code of Calendar class will give you the following output:

Calendar setTime(Date date) method example

Calendar setTime(Date date) method example

Exception Scenario :

Current time:Sun Jan 18 00:25:40 CST 2015
Exception in thread "main" java.lang.NullPointerException
	at java.util.Calendar.setTime(Calendar.java:1770)
	at com.javatutorialhq.java.examples.CalendarSetTimeExample.main(CalendarSetTimeExample.java:21)

A NullPointerException can be encountered if the Date method argument is null.

Similar Method :

  • getTime()
  • setTimeInMillis(long)

Suggested Reading List :

References :