I'm trying to convert a time in format "PT10H30M"
to format "10:30 AM"
and save this on Date
, time or timestamp variable in Java Android.
Any solution to do this?
I'm trying to convert a time in format "PT10H30M"
to format "10:30 AM"
and save this on Date
, time or timestamp variable in Java Android.
Any solution to do this?
Technically, PT10H30M
is not a time, it's a representing duration: an amount of time (an amount of 10 hours and 30 minutes). That string is in standard ISO 8601 format.
Although the "name" (10 hours and 30 minutes) is similar to 10:30 AM
(10 hours and 30 minutes AM), they're totally different concepts:
10:30 AM
represents a time of the dayPT10H30M
represents an amount of time - that can be, for example, added to a date/time:
01:00 AM
plus the duration of PT10H30M
results in 11:30 AM
11:00 PM
plus the duration of PT10H30M
results in 09:30 AM
of the next dayAnyway, you could achieve what you want by adding the duration of PT10H30M
to midnight (00:00
).
In Android you can use the ThreeTen Backport, a great backport for Java 8's new date/time classes. You'll also need the ThreeTenABP (more on how to use it here).
You can use a LocalTime
(which represents a time, with hour, minutes, seconds and nanoseconds), using a constant for midnight 00:00:00.0, and add a Duration
to it:
import org.threeten.bp.LocalTime;
import org.threeten.bp.Duration;
LocalTime time = LocalTime.MIDNIGHT.plus(Duration.parse("PT10H30M"));
The result will be a time
variable that holds the value corresponding to 10:30 AM
.
If you want the corresponding String
, you can use a org.threeten.bp.format.DateTimeFormatter
:
DateTimeFormatter fmt = DateTimeFormatter.ofPattern("h:mm a", Locale.ENGLISH);
System.out.println(time.format(fmt));
The result is a String
with the value 10:30 AM
. (Note that I also used a java.util.Locale
to make sure it properly formats the String
).