I've been looking at different methods to store time in Java and I can't quite find the right implementation for my needs.
I want to store information about our courses schedule, this information mainly consists of a starting and ending time(start:HH:MM end:HH:MM). Now I will be using this data throughout the code to create the different views and logic behind the app.
For now I've implemented it using the GregorianCalendar class which works fine but at each input of a course I end up using a default date for all + time, I then proceed on ignoring the date completely throughout the application.
I'm trying to develop better coding habits and was wondering how you would solve this problem. In our courses we get hammered on the head daily with good practices, OO development and using built in tools and library's when we can, but does this apply in such a situation?
should I:
Now obviously I'm not expecting a black and white answer here but more of a guideline in how to approach such problems.
EDIT:
I'm the original poster, I since registered an account but can't actually submit anything since I am not linked to the post.
After careful consideration I believe that building my own solution to store this information is the easiest and most intuitive approach, the tools that exist are brilliant but much more complex than the information I actually need and will probably lead to more bloated code to extract the items I require.
You probably should take a look at Joda Time. It is better than using just java.util.Date
or writing your own datetime implementation. Another plus of Joda Time is the object created is immutable and it has varieties of helpful APIs for manipulating the datetime or performing datetime checks.
There's class java.sql.Time
, which could serve this purpose, if it wasn't completely broken. I would NOT use Calender, as this is quite bloated class intended for computation and it contains a date part, too. I'd look at joda time, which most probable has what you need.
Otherwise, I'd go for my own class. You may need it in case you don't want to store seconds, etc.
Maybe consider just using an int to represent the time. This would be a value between 0 and 1439 (the number of minutes in the day). So noon would be represented as 720 (12 * 60); 9:30am would be 570 (9 * 60 + 30), 9:30pm would be 1290 (21 * 60 + 30), etc.
This could then be easily wrapped in a class to extract/set the hours and minutes (consider making this class immutable though).
JodaTime is an excellent library, but possibly overkill for what you are trying to do here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With