java.text.SimpleDateFormat format(Date date)

Description :

This java tutorial shows how to use the format(Date date) method of SimpleDateFormat class of java.text package. This method Formats a Date into a date/time string.

Method Syntax :

public final String format(Date date)

Parameter Input :

 

DataType Parameter Description
Date date the time value to be formatted into a time string.

 

Method Returns :

This method returns the formatted time string.

Compatibility Version :

Requires Java 1.2 and up

Exception :

N/A

Discussion :

This method is used widely in formatting the date input as specified by the pattern on the simpledateformat object. Together with the rest of format method of Simpledateformat, they are intended to help in dealing with different format required between applications. In real life programming, we would be dealing a lot of transformation of dates because of differences of format coming from different systems.

Java Code Example :

This java example source code demonstrates the use of format(Date date) method of SimpledDateFormat class.

package com.javatutorialhq.java.examples;

import java.text.SimpleDateFormat;
import java.util.Calendar;

/*
 * This example source code demonstrates the use of  
 * format(Date date) method 
 * of SimpleDateFormat class
 */

public class FormatDateExample {

	public static void main(String[] args) throws InterruptedException {

		// intialize simpledateformat
		SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");
		
		// instantiate calendar object
		Calendar cal = Calendar.getInstance();	
		
		// Print the current time
		System.out.println("Time 1:" + cal.getTime());
		
		// format the calendar date
		String formattedDate = sdf.format(cal.getTime());
		System.out.println("Formatted date:"+formattedDate);		

	}
	
}

Sample Output :

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

SimpleDateFormat format(Date date) method example

SimpleDateFormat format(Date date) method example

Exception Scenario :

N/A

Similar Method :

  • N/A

Suggested Reading List :

References :