Natalia Sharon
Natalia Sharon

Reputation: 317

Simple Date Format, Parsing Exception

Using Android Studio

I'm retrieving a date from facebook, it comes as a string "2015-11-21T17:49:49+0000"

I wish to turn it into a date with format "EEE MMM dd HH:mm:ss Z yyyy" but of course I need to first change it into a Date object

Attempting to do that, I've attempted to parse it into "EEE-MM-dd'T'HH:mm:ssZyyyy" but this causes my program to crash. "ParseException: Unparseable date: "2015-11-21T17:49:49+0000" (at offset 0)"

Could it be the T symbol coming with the date? Or am I using an incorrect format?

Upvotes: 1

Views: 1509

Answers (3)

Aurelien
Aurelien

Reputation: 458

You can use JodaTime as external library. Once this library is inside your classpath all you have to do is to write something like this:

DateTime myDate = new DateTime("2015-11-21T17:49:49+0000");

You can then convert it into Date object calling toDate() method on myDate.

Upvotes: 0

Alexander Guyer
Alexander Guyer

Reputation: 2203

You could also use a GregorianCalendar. Though they take longer to define, they are simpler to manage.

GregorianCalendar calendar = new GregorianCalendar();

int year, month, day, hour, minute, second;

//...parse the data and store year, month, day, hour, minute, and second.
//...
//...

//fill in calendar's data.
calendar.set(Calendar.YEAR, year);
calendar.set(Calendar.MONTH, month - 1); //month is offset by one (January == 0)
calendar.set(Calendar.DAY_OF_MONTH, day);
calendar.set(Calendar.HOUR, hour); //No need to edit. 12AM is 0, 1AM is 1, 12PM is 12, etc.
calendar.set(Calendar.MINUTE, minute);
calendar.set(Calendar.SECOND, second);

//get time in milliseconds since epoch and create Date object.
Date date = new Date(calendar.getTimeInMillis());

Upvotes: 0

Elliott Frisch
Elliott Frisch

Reputation: 201537

Your input format needs yyyy (not EEE). Something like,

String in = "2015-11-21T17:49:49+0000";
String fmtIn = "yyyy-MM-dd'T'HH:mm:ssZ";
String fmtOut = "EEE MMM dd HH:mm:ss Z yyyy";
DateFormat sdf = new SimpleDateFormat(fmtIn);
try {
    Date d = sdf.parse(in);
    DateFormat outSDF = new SimpleDateFormat(fmtOut);
    System.out.println(outSDF.format(d));
} catch (ParseException e) {
    e.printStackTrace();
}

Output (because I'm in EST) is

Sat Nov 21 12:49:49 -0500 2015

Upvotes: 4

Related Questions