How to format a date in Java

This tutorial shows how to formate a Date in Java.

Java uses the SimpleDateFormat to format dates.

Create the following java file:

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

public class DateFormatting {

	public static void main(String[] argv){
		// Create the pattern 	
		String pattern = "yyyy-MM-dd";
		SimpleDateFormat simpleDateFormat = new SimpleDateFormat(pattern);
		
		// Create the date with the current time
		Date now = new Date();
		
		System.out.println( "Formatted date: " + simpleDateFormat.format( now ) ); 

		
		
		// Create the French formatter
		SimpleDateFormat simpleDateFormatFrench = new SimpleDateFormat("EEEEE dd MMMMM yyyy", Locale.FRENCH);

		System.out.println( "Formatted date: " + simpleDateFormatFrench.format( now ) ); 

		// Create the english Formatter
		SimpleDateFormat simpleDateFormatEnglish = new SimpleDateFormat("EEEEE dd MMMMM yyyy", Locale.ENGLISH);

		System.out.println( "Formatted date: " + simpleDateFormatEnglish.format( now ) ); 
	}
	
}

The output will be:

	
Formatted date: 2016-10-05
Formatted date: mercredi 05 octobre 2016
Formatted date: Wednesday 05 October 2016
	

The example first creates a simpleDateFormat with the default pattern. Then it creates a Date for called now of type Date. That date is passed to the format method of hte simpleDateFormater and to create the String to display.
The same formatter is created with the French locale to renderer the String in French. If Locale.ENGLISH is passed to the contructor then the String Wednesday is returned instead of mercredi.

References:

SimpleDateFormat

Share this article:

Recent Comments