August 11 2016

Java get month from date

Java get month from date 

To get the month from a java.util.Date object, we can use the java.text.SimpleDateFormat class or java.util.Calendar.

Example

JavaGetMonthFromDate.java

package test;

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

public class JavaGetMonthFromDate {

 public static void main(String[] args) throws ParseException {

 // Java get month from date

 Date currentDate = new Date();

 // Using Calendar returns (0-11). Month start from 0

 Calendar cal = Calendar.getInstance();
 cal.setTime(currentDate);
 int month = cal.get(Calendar.MONTH);
 System.out.println("Month Using Calendar :" + (month + 1));

 // Using SimpleDateFormat
 // MM(Numeric)/MMM(Three digit abbreviation)/MMMM(full month name)

 SimpleDateFormat dateFormat = new SimpleDateFormat("MM");
 int mnt = Integer.parseInt(dateFormat.format(currentDate));
 System.out.println("Month Using SimpleDateFormat Numeric : " + mnt);

 // Using SimpleDateFormat String
 SimpleDateFormat dateFormat2 = new SimpleDateFormat("MMM");
 String mnth = dateFormat2.format(currentDate);
 System.out.println("Month Using SimpleDateFormat String : " + mnth);

 }
}

Output

Month Using Calendar :8
Month Using SimpleDateFormat Numeric : 8
Month Using SimpleDateFormat String : Aug


Copyright © 2014. All rights reserved.

Posted August 11, 2016 by answersz in category Core Java

Leave a Comment

Your email address will not be published. Required fields are marked *

*