Reputation:
I am trying to change the date format from a JSON response, but I keep getting java.text.ParseException
.
This is the date from the server 2015-02-03T08:37:38.000Z
and I want it to show as 2015/02/03
That's yyyy-MM-dd
. And I did this.
DateFormat df1 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
SimpleDateFormat dateFormatter = new SimpleDateFormat("yyyy-MM-dd");
String dateResp = transactionItem.get(position).getDate();
try {
Date date = df1.parse(dateResp);
transDate.setText(dateFormatter.format(date));
} catch (ParseException e) {
e.printStackTrace();
}
But the exception keeps showing.
Upvotes: 2
Views: 931
Reputation: 338584
Instant.parse( "2015-02-03T08:37:38.000Z" )
.atZone( ZoneId.of( "America/Montreal" ) )
.toLocalDate()
.toString() // 2015-02-03
The modern way to handle date-time work is with the java.time classes.
Your input string format happens to comply with the ISO 8601 standard. The java.time classes use ISO 8601 formats by default when parsing/generating strings that represent date-time values. So no need to specify a formatting pattern at all.
Parse that string as an Instant
. The Instant
class represents a moment on the timeline in UTC with a resolution of nanoseconds (up to nine (9) digits of a decimal fraction).
Instant instant = Instant.parse( "2015-02-03T08:37:38.000Z" ) ;
To extract a date, you must specify a time zone. For any given moment the date varies around the globe by zone. For example, a moment after midnight in Paris France is a new day while still “yesterday” in Montréal Canada.
ZoneId z = ZoneId.of( "America/Montreal" );
ZonedDateTime zdt = instant.atZone( z );
You want only the date portion without the time of day. So extract a LocalDate
. While a LocalDate
lacks any concept of offset-from-UTC or time zone, the toLocalDate
method respects the ZonedDateTime
object’s time zone in determining the date.
LocalDate ld = zdt.toLocalDate();
You seem to want standard ISO 8601 format, YYYY-MM-DD
. Simply call toString
without need to specify a formatting pattern.
String output = ld.toString();
2015-02-03
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date
, Calendar
, & SimpleDateFormat
.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
Where to obtain the java.time classes?
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval
, YearWeek
, YearQuarter
, and more.
Upvotes: 0
Reputation: 5751
You must escape the Z
:
"yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"
Try to use this for formatting purpose instead of your provided formatting string. It should work nicely :)
Upvotes: 12