Reputation: 3956
Given the float x = 1500, is there a built in object that can return the string "00:00:01:30" In my case the float represents milliseconds passed and I want to print the string version of it.
System.out.println(????.Stringvalue(x)); //for example
Upvotes: 0
Views: 303
Reputation: 714
I doubt there's a built-in method that does this for you, but it should be fairly simple for you to do on your own using a combination of division and the %
modulo operator.
In this example, you know that 1500 / 1000 = 1 second. 1500 % 1000 will give you 500, or the remaining milliseconds after taking that 1 second into account. This can be extended repeatedly if you start with a larger number of milliseconds.
I'm not sure why you have 500 milliseconds written as "30", however. Usually, after seconds would come plain milliseconds, so it would look like "00:00:01:500".
Upvotes: 4
Reputation: 5122
Here you go, hugely inefficient, and total overkill, but hey-ho:
DateFormat df = new SimpleDateFormat("HH:mm:ss.SSS");
df.setTimeZone(TimeZone.getTimeZone("GMT"));
System.out.println(df.format(new Date((long) x)));
Note: Your millis are truncated down not rounded to the nearest milli.
Upvotes: 0
Reputation: 1296
There IS a way to format your value as you wish. But, you will need to convert your FLOAT to a LONG. Why use a float anyway?
You can use the org.apache.commons.lang3.time.DurationFormatUtils.
DurationFormatUtils.formatDurationHMS(longValue);
Will return the standard ISO8601 format. "00:00:01:500"
Please see Standard ISO8601 Format.
Upvotes: 0
Reputation: 359986
There is no such built-in object to represent any sort of time duration, so no. It is fairly simple to roll your own, or as always, just use Joda Time.
long x = 1500; // Don't use floats to store milliseconds.
Duration d = new Duration(x);
String formatted = String.format("%02d:%02d:%02d.%02d",
d.getStandardHours(),
d.getStandardMinutes(),
d.getStandardSeconds(),
d.getMillis() % 1000);
System.out.println(formatted); // 00:00:01.500
Upvotes: 2