String realTimeStr = "5.2345";
Double realTimeDbl = Double.parseDouble(realTimeStr);
long realTimeLng = (long) (realTimeDbl*1000);
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss.SSSS", Locale.getDefault());
log("Duration: " + sdf.format(new Date(realTimeLng - TimeZone.getDefault().getRawOffset())));
Current output:
Duration: 00:00:05.0234
Desired output:
Duration: 00:00:05.2345
I also tried another method, still no good:
String realTimeStr = "1.4345";
Double realTimeDbl = Double.parseDouble(realTimeStr);
DateTimeFormatter formatter =
DateTimeFormatter.ofPattern("HH:mm:ss.SSSS").withZone(ZoneId.of("UTC"));
Instant instant = Instant.ofEpochMilli((long)(realTimeDbl*1000));
String t = formatter.format(instant);
System.out.println("Duration: " + t);
Current output:
Duration: 00:00:01.4340
Desired output:
Duration: 00:00:01.4345
I have googled for some time. Any ideas what is causing this?
The problem resides in the format, as noticed by Joe C, probably meaning at this line:
try changing it removing one "S"
notify us if it's correct =)
First of all, you're mistaking 2 different concepts:
10 AM
or15:30:45
Although both might use the same words (such as "hours" and "minutes"), they're not the same thing. A duration is not attached to a chronology (10 hours and 25 minutes relative to what?), it's just the amount of time, by itself.
SimpleDateFormat
andDateTimeFormatter
are designed to format dates and times of the day, but not durations. Although converting a duration to a time and "pretending" it's a time of the day to format it might work, it's not the right way.Unfortunately, there are no built-in formatters for a duration. So you'll have to format it manually.
Another detail is that you are multiplying
1.4345
by 1000 (resulting in1434.5
), and then casting to along
(so the value is rounded to1434
) - the last digit is lost.One way to do it is to parse the string to a double and then multiply by 1 billion to get the value as nanoseconds (I don't know if you'll work with more than 4 digits, so I'm considering nanosecond precision):
Now we must format it manually. First I've extracted the number of hours, minutes, seconds and nanoseconds from the total nanos value:
Then I created an auxiliary method to build the output:
And used it to join the pieces:
The output is:
I tried
SSSs
instead ofSSSS