Date and Time

Java SimpleDateFormat Code With Examples

Table of Contents

Program

import java.text.SimpleDateFormat;
import java.util.Date;

public class Display {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Date objDate = new Date(); 
		  System.out.println(objDate);
		  String strDateFormat = "yyyy-MMM-dd a hh:mm:ss"; 
		  SimpleDateFormat objSDF = new SimpleDateFormat(strDateFormat); 
		  System.out.println(objSDF.format(objDate)); 
	}

}

Output

	Thu Apr 08 14:15:56 IST 2021
	2021-Apr-08 PM 02:15:56

Description

public StringBuffer format​(Date date, StringBuffer toAppendTo, FieldPosition pos)

Formats the given Date into a date/time string and appends the result to the given StringBuffer.
Specified by:format in class DateFormat

Specified by:

format in class DateFormat

Parameters:

date – the date-time value to be formatted into a date-time string.

toAppendTo – where the new date-time text is to be appended.
pos – keeps track on the position of the field within the returned string. For example, given a date-time text “1996.07.10 AD at 15:08:56 PDT”, if the given fieldPosition is DateFormat.YEAR_FIELD, the begin index and end index of fieldPosition will be set to 0 and 4, respectively. Notice that if the same date-time field appears more than once in a pattern, the fieldPosition will be set for the first occurrence of that date-time field. For instance, formatting a Date to the date-time string “1 PM PDT (Pacific Daylight Time)” using the pattern “h a z (zzzz)” and the alignment field DateFormat.TIMEZONE_FIELD, the begin index and end index of fieldPosition will be set to 5 and 8, respectively, for the first occurrence of the timezone pattern character ‘z’.

Returns:

the formatted date-time string.

Throws:

NullPointerException – if any of the parameters is null.

Returns: