Wednesday, May 4, 2011

Get Month from Date Object in Java

To get the month from a java.util.Date object, we can use the java.text.SimpleDateFormat class. First, create a Date object. Next, create a SimpleDateFormat instance using the getDateInstance() method, passing the String "MM", "MMM", or "MMMM" as the argument. Finally, get the month as a String using the format() method passing in the java.util.Date object.

Get Month from Date in Java - Example Code

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

//
//The following example code demonstrates how to
//print out the Month from a Date object.
//
public class GetMonthFromDate {

    public static void main(String[] args) {

        Date now = new Date();
        SimpleDateFormat simpleDateformat = new SimpleDateFormat("MM"); // two digit numerical represenation
        System.out.println(simpleDateformat.format(now));

        simpleDateformat = new SimpleDateFormat("MMM"); // three digit abbreviation
        System.out.println(simpleDateformat.format(now));

        simpleDateformat = new SimpleDateFormat("MMMM"); // full month name
        System.out.println(simpleDateformat.format(now));

    }

}

Here is the output of the example code:
05
May
May

No comments: