Search code examples
classtimejavahour

Is there a class in JDK to represent an hour of the day, but not necessarily a specific hour at a specific date?


Is there a class in JDK or Guava to represent an hour of the day, but not necessarily a specific hour at a specific date? If not, why?


Solution

  • In JDK 1.3-1.7, the answer is no. A specific time within a day is much easier to calculate then date, because you don't have to deal with leap year, leap month, such headache stuff. A simple integer is just enough. When you need to convert the time to a locale string, using SimpleDateFormatter or whatever, you can simply convert the time to a Date, just ignore the date part:

    int time = 8 * 60 + 34; // 8:34 am
    Date date = new Date(60000L * time);
    

    Reset the time zone to +0, and pass the date to the formatter:

    SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
    sdf.setTimeZone(TimeZone.getTimeZone("GMT+0"));
    sdf.format(date);