Reputation: 27257
Am trying to convert a Date
String to Date but SimpleDateFormat.parse
returns nothing when I add the time.
This is the Date String:
String dateInString = news.getDate();
Log.e(TAG, "Date in String: " + dateInString);
Date in String: 2015-08-19T06:21:59+01:00 //Result
When I do:
DateFormat format
= new SimpleDateFormat("yyyy-MM-dd", Locale.ENGLISH);
Date date;
try {
date = format.parse(dateInString);
Log.e(TAG, "Formatted date: " + date);
} catch (ParseException e) {
e.printStackTrace();
}
I get the result: Formatted date: Wed Aug 19 01:00:00 GMT+01:00 2015
If I add the time to SimpleDateFormat:
DateFormat format
= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.ENGLISH);
the code doesn't even get past the try and no exception is thrown.Nothing just gets printed.
I have tried adding the TimeZone
with no luck:
TimeZone timeZone = TimeZone.getTimeZone("UTC+01"); //also tried GMT+1:00, UTC+1:00 and UTC
DateFormat format
= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.ENGLISH);
format.setTimeZone(timeZone);
try {
date = format.parse(dateInString);
Log.e(TAG, "Formatted date: " + date);
} catch (ParseException e) {
e.printStackTrace();
}
Any pointers?
Upvotes: 0
Views: 413
Reputation: 4029
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssXXX",Locale.ENGLISH);
'X' flag is available since 1.7 and it represents Timezone.
All available flags are described here http://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html
Upvotes: 0
Reputation: 27257
I guess there are several ways to do this. In addition to Arturo's answer, this also works:
DateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ", Locale.English);
Upvotes: 0
Reputation: 548
The pattern sed for SimpleDataFormat is incorrect, use this one:
DateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZZZZZ", Locale.ENGLISH);
Notice the pattern is slightly different, I've added a T text separating date and time and also the ZZZZZ
which says there is timezone there.
Upvotes: 1