java.time and ThreeTenABP
It’s not the answer that you asked for, but it should be the answer that other readers want in 2020 and onward.
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MM/dd/uuuu HH:mm:ss");
String result = "11/08/2013 08:48:10";
LocalDateTime dateTime = LocalDateTime.parse(result, formatter);
System.out.println("Parsed date and time: " + dateTime);
Output from this snippet is:
Parsed date and time: 2013-11-08T08:48:10
The Date
class that you used is poorly designed and long outdated, so don’t use that anymore. Instead I am using java.time, the modern Java date and time API. If you need a Date
for a legacy API that you cannot afford to upgrade just now, the conversion is:
Instant i = dateTime.atZone(ZoneId.systemDefault()).toInstant();
Date oldfashionedDate = DateTimeUtils.toDate(i);
System.out.println("Converted to old-fashioned Date: " + oldfashionedDate);
Converted to old-fashioned Date: Fri Nov 08 08:48:10 CET 2013
What went wrong in your code?
what's wrong with it ?
The only thing wrong with your code is you’re using the notoriously troublesome SimpleDateFOrmat
and the poorly designed Date
class. Which wasn’t wrong when you asked the question in 2013. java.time didn’t come out until 4 months later.
Your code is running fine. One may speculate that a leading space or the like in your string has prevented parsing. If this was the problem, try parsing result.trim()
rather than just result
since trim()
returns a string with the leading and trailing whitespace removed.
Question: Doesn’t java.time require Android API level 26?
java.time works nicely on both older and newer Android devices. It just requires at least Java 6.
- In Java 8 and later and on newer Android devices (from API level 26) the modern API comes built-in. Only in this case the conversion to
Date
is a little simpler: Date.from(i)
.
- In non-Android Java 6 and 7 get the ThreeTen Backport, the backport of the modern classes (ThreeTen for JSR 310; see the links at the bottom).
- On (older) Android use the Android edition of ThreeTen Backport. It’s called ThreeTenABP. And make sure you import the date and time classes from
org.threeten.bp
with subpackages.
Links