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.
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.
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.
I’ve looked at a lot of different solutions, and in my humble opinion Aspose is the way to go. Here’s the link: http://aspose.com