What is the most efficient method of converting an int val to its string counterpart in this format - "HH:MM:SS"
10 becomes 00:00:10
70 becomes 00:01:10
3610 becomes 01:00:10
I need this to be JDK1.4 compliant.
What I've come up with is a series of if statements and then constructing a string based on the current int val. This is not very efficient. Is there a better way?
How about this (I made it in my last project):
This is what I do:
But using a StringBuffer instead of String.format could be faster. Just try it.
You need to clarify your definition of "efficient". To me efficient is "doesn't requiring to reinvent the wheel myself". Which means using libraries (yes,
java.util.Calendar
is quite outdated, but still better than coding it yourself):All of
Calendar
,Date
andSimpleDateFormat
are compatible with JDK 1.4.Instead of a heap of code, how about just one line?
p.s. I never fails to amaze me just how much code some people write to do the simplest of things
The timezone is set to UTC, because SimpleDateFormat uses your locale to format the date. For example my timezone is GMT+10 and if I format
new Date(0)
, the time part is "10:00:00".For those who don't recognise that odd syntax where the timezone is being set, it's an anonymous class with an "instance block", which gets executed on construction, after the constructor has finished.