Date and Time

SimpleDateformat in java To Display Date in different formats

Table of Contents

Program

// SimpleDateFormat to print date in different format
import java.text.Format;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

public class DateTimeFormatingPattern {

	public static void main(String[] args) {
		// TODO Auto-generated method stub

	      Calendar cal = Calendar.getInstance();
	      SimpleDateFormat simpleformat = new SimpleDateFormat("dd/MMMM/yyyy hh:mm:s");
	      System.out.println("Today's date and time = "+simpleformat.format(cal.getTime()));
	    
	      Format f = new SimpleDateFormat("MM/dd/yy");
	      String strDate = f.format(new Date());
	      System.out.println("Current Date = "+strDate);
	      
	      f = new SimpleDateFormat("HH.mm.ss ");
	      String strTime = f.format(new Date());
	      System.out.println("Current Time = "+strTime);
	    
	      f = new SimpleDateFormat("H");
	      String strHour = f.format(new Date());
	      System.out.println("Current Hour = "+strHour);
	      
	      f = new SimpleDateFormat("mm");
	      String strMinute = f.format(new Date());
	      System.out.println("Current Minutes = "+strMinute);
	   
	      f = new SimpleDateFormat("ss");
	      String strSeconds = f.format(new Date());
	      System.out.println("Current Seconds = "+strSeconds);
	   }
	}

Output

Today's date and time = 08/April/2021 02:39:23
	Current Date = 04/08/21
	Current Time = 14.39.23 
	Current Hour = 14
	Current Minutes = 39
	Current Seconds = 23

Description

public static Calendar getInstance()

Gets a calendar using the default time zone and locale. The Calendar returned is based on the current
time in the default time zone with the default FORMAT locale.
If the locale contains the time zone with “tz” Unicode extension, that time zone is used instead.

Returns:

a Calendar.

public final Date getTime()

Returns a Date object representing this Calendar’s time value (millisecond offset from the Epoch”).

Returns:

a Date representing the time value.

Returns:

setTime(Date), getTimeInMillis()

public final String format​(Object obj)

Formats an object to produce a string. This is equivalent to
format(obj, new StringBuffer(), new FieldPosition(0)).toString();

Parameters:

obj – The object to format

Returns:

Formatted string.

Throws:

IllegalArgumentException – if the Format cannot format the given object