Two Laptop Bag*
The moose likes Java in General and the fly likes Math on Time of Day Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "Math on Time of Day" Watch "Math on Time of Day" New topic
Author

Math on Time of Day

Wally Hartshorn
Ranch Hand

Joined: Jan 30, 2003
Posts: 77
Suppose that you have a time of day in the form of a string, such as "12:15 PM". You want to be able to add some arbitrary amount of minutes to that time to get a new time string. You don't care about the date, only the time (so you don't care whether "11:30 PM" plus 60 minutes rolls over to the next day).

What would be the best way to write a function to handle this? (No, it's not a homework assignment.)

My guess is to pass the time string to the SimpleDateFormat parse() function to get a Date object, then use that to initialize a GregorianCalendar object, then perform the math, then reverse the process to get the new time string, such as "12:45 PM".



I don't expect execution time to be a factor, but the conversions to a Date object, then to a GregorianCalendar object, and then back to a Date object feel somewhat annoying.

Is there a better way to do this?

The only other way I can think of to do it would be to convert the time string into minutes since midnight, do the math, and then convert back. I suspect that would be even more annoying.


Wally Hartshorn
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 37874
    
  22
If you really only want hours minutes and seconds, consider a TimeOfDay class with the three fields hours minutes and seconds. You can use the % operator to change the time when you go past midnight. Most simple implementations will record midnight as 00:00:00 rather than 24:00:00.
Paul Clapham
Bartender

Joined: Oct 14, 2005
Posts: 18541
    
    8

You don't care about the date? Does that mean that you want "1:30 AM" plus 60 minutes to always be "2:30 AM"? You know that in places where daylight saving time is in force, the answer to that is "3:30 AM" on one day each year and "1:30 AM" on one day each year, right?

If your answer to that is that you don't care about that and always want "2:30 AM" for that then your suggestion of parsing the string to a Calendar, doing the arithmetic, and formatting to a new string is still the best idea. Just force the date in the Calendar to be some day in January so that it isn't one of the DST cutover dates.
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: Math on Time of Day
 
Similar Threads
Adjusting GregorianCalendar to reflect a specific TimeZone
Adding value to A Time
DateTime Problem
48 hours rule, pls recomment
weird java dates!!!!