Java Date to Month getMonthOfYear(final Date date)

Here you can find the source of getMonthOfYear(final Date date)

Description

Get the month of year by given date.

License

Apache License

Parameter

Parameter Description
date date to be handled.

Return

the month of year by given date.

Declaration

public static int getMonthOfYear(final Date date) 

Method Source Code

//package com.java2s;
//License from project: Apache License 

import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;

public class Main {
    private static final ThreadLocal<Calendar> calendarCache = new ThreadLocal<Calendar>();

    /**/*from   w  w w  .  j  a  va 2s. c o  m*/
     * Get the month of year by given date. This is a calendar-specific value. The
     * first month of the year in the calendars is JANUARY which is 1; the last
     * depends on the number of months in a year.
     * 
     * @param date date to be handled.
     * @return the month of year by given date.
     */
    public static int getMonthOfYear(final Date date) {

        return getNumberOfGranularity(Calendar.MONTH, date) + 1;
    }

    private static int getNumberOfGranularity(final int granularity, final Date date) {

        Calendar calendar = buildCalendar(date);
        return calendar.get(granularity);
    }

    /**
     * Gets a calendar using the default time zone and locale. The Calendar
     * returned is based on the current time in the default time zone with the
     * default locale.
     * 
     * @return a Calendar object.
     */
    private static Calendar buildCalendar() {

        Calendar calendar = calendarCache.get();
        if (calendar == null) {
            calendar = GregorianCalendar.getInstance();
            calendarCache.set(calendar);
        }
        return calendar;
    }

    /**
     * Gets a calendar using the default time zone and locale. The Calendar
     * returned is based on the given time in the default time zone with the
     * default locale.
     * 
     * @return a Calendar object use given date.
     */
    private static Calendar buildCalendar(final Date date) {

        Calendar calendar = buildCalendar();
        calendar.setTime(date);
        return calendar;
    }
}

Related

  1. getMonthOfCurrentTime(Date date)
  2. getMonthOffset(Date sourceDate, Date targetDate)
  3. getMonthOfThisYear(Date currentdate)
  4. getMonthOfYear(Date date)
  5. getMonthOfYear(Date dt)
  6. getMonthRate(Date date, boolean moveIn)
  7. getMonths(Date date1, Date date2)
  8. getMonthStart(Date date)
  9. getMonthStart(Date date)