I should like to contribute the modern answer.
java.time and ThreeTenABP
DateTimeFormatter dateFormatter
= DateTimeFormatter.ofLocalizedDate(FormatStyle.LONG);
String uploadeddate = "2011-03-27T09:39:01.607";
LocalDateTime ldt = LocalDateTime.parse(uploadeddate);
String actDate = ldt.format(dateFormatter);
System.out.println(actDate);
When I set my default locale to English and run this snippet, the output is what you asked for:
March 27, 2011
I am exploiting the fact that your string is in the standard ISO 8601 format, and that the classes of java.time parse this format as their default. Usually when reformatting a date/time string from one format to another, two formatters are used, one that specifies the format to convert from and one for the format to convert to. But since your source format is the default, we can make do with only one formatter here.
What went wrong in your code?
- Your counting is wrong:
uploadeddate.substring(0,9)
gives you 2011-03-2
where I’m sure you intended 2011-03-27
.
- You passed a
String
to formats[0].format()
, but it cannot format a string. It accepts either a Date
or a Long
, so you would have needed to convert to one of these first. The code compiles, but throws java.lang.IllegalArgumentException: Cannot format given Object as a Date
.
Question: Can I use java.time on Android?
Yes, java.time works nicely on 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.
- In 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