How to get datefields(date,month,year) from datetime in java

Here we will learn how to fetch the date fields from Calendar date. Date fields could be anything from Day, Month, Year.

Here we will use getDisplayName(int field, int style,  Locale locale) method from the Calendar abstract class. This method returns the string representation of the calendar field value in the given style and locale. For complete list of Calendar field visit here.

 

import java.util.Calendar;
import java.util.Locale;

public class GetCalendarFields {

	public static void main(String args[]) {
		Calendar calendar = Calendar.getInstance();
		/*
		 * These methods will return the number representation of calendar field
		 */
		System.out.println(calendar.get(Calendar.DATE));
		System.out.println(calendar.get(Calendar.MONTH));
		System.out.println(calendar.get(Calendar.YEAR));

		/*
		 * Below methods will return the string representation of calendar
		 * fields
		 */

		System.out.println(calendar.getDisplayName(Calendar.MONTH,
				Calendar.SHORT, Locale.US));
		System.out.println(calendar.getDisplayName(Calendar.DAY_OF_WEEK,
				Calendar.SHORT, Locale.US));
		System.out.println(calendar.getDisplayName(Calendar.AM_PM,
				Calendar.SHORT, Locale.US));

	}
}

Output of the above code would be

 

21
6
2012
Jul
Sat
PM

 

By | 2012-07-21T15:12:38+00:00 July 21st, 2012|Code Base|0 Comments

About the Author:

Leave A Comment