简体   繁体   中英

SimpleDateFormat parse returns nothing when working with time

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?

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.

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

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM