I have a problem with time format.Some time I have values in hh:mm:ss and some times in mm:ss format.
My code looks like:
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
String time = "01:48:00"
Date remainedTimeDate = sdf.parse(time);
It works, when I got format hh:mm:ss but when I have time in format mm:ss I got an error like, value can not be parsed. Is it possible to dynamically change date format?
Assuming that your string denotes an amount of time (for example, a duration), the right class to use for it in Java is Duration
from java.time, the modern Java date and time API. Unfortunately Duration
cannot parse your strings out of the box. It has a parse
method that only accepts ISO 8601 format. ISO 8601 format for a duration goes like for example PT1H48M30S
. It looks unusual at first, but is straightforward to read when you know how. Read the example just given as a period of time of 1 hour 48 minutes 30 seconds. So to parse your strings in hh:mm:ss and mm:ss format I first convert them to ISO 8601 using a couple of regular expressions.
// Strings can be hh:mm:ss or just mm:ss
String[] examples = { "01:48:30", "26:57" };
for (String example : examples) {
// First try to replace form with two colons, then form with one colon.
// Exactly one of them should succeed.
String isoString = example.replaceFirst("^(\\d+):(\\d+):(\\d+)$", "PT$1H$2M$3S")
.replaceFirst("^(\\d+):(\\d+)$", "PT$1M$2S");
Duration dur = Duration.parse(isoString);
System.out.format("%8s -> %-10s -> %7d milliseconds%n", example, dur, dur.toMillis());
}
In addition my code also shows how to convert each duration to milliseconds. Output is:
01:48:30 -> PT1H48M30S -> 6510000 milliseconds 26:57 -> PT26M57S -> 1617000 milliseconds