I'm stuck with converting DateTime format to String, I just can't get any idea how to get only Hours Minutes and Seconds from this type correctly. When I tried my way I get something like 2020-01-17T20:19:00
. But I need to get just 20:19:00
.
import org.joda.time.DateTime;
public DateTime orderDateFrom;
Log.d(TAG, orderDateFrom.toString());
Since you are already using Joda-Time, I recommend you choose between two options:
The option I certainly whole-heartedly discourage is going back to Date
and SimpleDateFOrmat
from Java 1.0 and 1.1. Those classes are poorly designed and long outdated, the latter in particular notoriously troublesome.
If you want the time from your DateTime
formatted into a String
, for example for output to the user:
DateTime orderDateFrom = new DateTime(2020, 1, 17, 20, 19, 0, DateTimeZone.forID("Mexico/BajaSur"));
DateTimeFormatter timeFormatter = DateTimeFormat.forPattern("HH:mm:ss");
String formattedTime = orderDateFrom.toString(timeFormatter);
System.out.println("Order time: " + formattedTime);
Output from this snippet is:
Order time: 20:19:00
If you want the time of day as an object that you can use for further procesing:
LocalTime orderTime = orderDateFrom.toLocalTime();
System.out.println("Order time: " + orderTime);
Order time: 20:19:00.000
We notice that this time three decimals on the second of minute are also printed since the no-arg toString
method does that. You can format the LocalTime
using the same formatter as above to obtain the same string if you like.
If programming for Android API level 26 and/or above, java.time comes built-in. If you need to take lower API levels into account, java.time comes as an external dependency just like Joda-Time: the ThreeTenABP. That’s ThreeTen for JSR-310, where java.time was first described, and ABP for Android Backport. See the links at the bottom.
The code will be similar, not identical to the code using Joda-Time above.
java.time
to Java 6 and 7.