text

Format date in default formats with DateFormat

With this example we are going to demonstrate how to format a date in default formats with DateFormat. Default formats are provided by the DateFormat API to control the length of the result, from SHORT, MEDIUM to LONG and FULL. In short, to format a date in default formats with DateFormat you should:

  • Create a new Date.
  • For each one of the default formats invoke the getDateInstance(int style) API method to get the date formatter with the specific formatting style.
  • Then invoke the format(Date date) API method to format the Date into a date string.

Let’s take a look at the code snippet that follows:

package com.javacodegeeks.snippets.core;

import java.text.DateFormat;
import java.util.Date;

public class FormatDateInDefaultFormatsWithDateFormat {
	
	public static void main(String[] args) {
		
		Date now = new Date();
		 
		// format date in Short format
		String strDate = DateFormat.getDateInstance(DateFormat.SHORT).format(now);
		System.out.println(strDate);
		 
		// format date in Medium format
		strDate = DateFormat.getDateInstance(DateFormat.MEDIUM).format(now);
		System.out.println(strDate);
		 
		// format date in Long format
		strDate = DateFormat.getDateInstance(DateFormat.LONG).format(now);
		System.out.println(strDate);
		 
		// format date in Full format
		strDate = DateFormat.getDateInstance(DateFormat.FULL).format(now);
		System.out.println(strDate);
		
	}

}

Output:

10/20/11
Oct 20, 2011
October 20, 2011
Thursday, October 20, 2011

 
This was an example of how to format a date in default formats with DateFormat in Java.

Ilias Tsagklis

Ilias is a software developer turned online entrepreneur. He is co-founder and Executive Editor at Java Code Geeks.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Inline Feedbacks
View all comments
Back to top button