How to Format Months Using Java SimpleDateFormat


In this example we will show how to format months with Java SimpleDateFormat class. Month can be formatted in different ways and the common formats include M, MM, MMM and MMMM. Below a few examples are given to demonstrate them.

Source Code

package com.beginner.examples;

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

public class FormattingMonth {

	public static void main(String[] args) {
		
		//create Date.
		Date date = new Date();
		
		System.out.println("Before formatting , date is : " + date);
		
		/*
		 * To format month in M format use SimpleDateFormat("M") Constructor.
		 */
		SimpleDateFormat simpleDateFormat1 = new SimpleDateFormat("M");
		System.out.println("Current Month in M format : " + simpleDateFormat1.format(date));
		
		/*
		 * To format month in MM format use SimpleDateFormat("MM") Constructor.
		 */
		SimpleDateFormat simpleDateFormat2 = new SimpleDateFormat("MM");
		System.out.println("Current Month in MM format : " + simpleDateFormat2.format(date));
		
		/*
		 * To format month in MMM format use SimpleDateFormat("MMM") Constructor.
		 */
		SimpleDateFormat simpleDateFormat3 = new SimpleDateFormat("MMM");
		System.out.println("Current Month in MMM format : " + simpleDateFormat3.format(date));
		
		/*
		 * To format month in MMMM format use SimpleDateFormat("MMMM") Constructor.
		 */
		SimpleDateFormat simpleDateFormat4 = new SimpleDateFormat("MMM");
		System.out.println("Current Month in MMMM format : " + simpleDateFormat4.format(date));
		
	}

}

Output:

Before formatting , date is : Fri Jun 14 14:41:17 CST 2019
Current Month in M format : 6
Current Month in MM format : 06
Current Month in MMM format : Jun
Current Month in MMMM format : June

References

Imported packages in Java documentation:

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments