Java Hour getHourOfDay(final Date date)

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

Description

Get the hour of the day by given date.

License

Apache License

Parameter

Parameter Description
date date to be handled.

Return

the hour of the day by given date.

Declaration

public static int getHourOfDay(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  v  a 2s. c o  m
     * Get the hour of the day by given date. HOUR_OF_DAY is used for the 24-hour
     * clock(0-23).<br>
     * E.g.: at 10:04:15.250 PM the HOUR_OF_DAY is 22.
     * 
     * @param date date to be handled.
     * @return the hour of the day by given date.
     */
    public static int getHourOfDay(final Date date) {

        return getNumberOfGranularity(Calendar.HOUR_OF_DAY, date);
    }

    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. getHourMin(Date date)
  2. getHourMinuteSecondByMisSecond(long misSecond)
  3. getHourMinuteString(Date dateTime)
  4. getHourMinuteString(Date t)
  5. getHourOfDay(Calendar date)
  6. getHourOfDayInAm(Date dt)
  7. getHourOfWeek(Date dateIn)
  8. getHours()
  9. getHours()