简体   繁体   中英

Android parse pubDate tag from RSS xml feed

I'm having problem parsing the tag from an RSS Feed.

The format is like this: Mon, 16 Apr 2012 16:42:30 +0000

I created a function parseDate which does the trick, but the fact is it parses the date using Locale.US, which returns the date but using the US locale, so it returns the time +2 hours. If I don't provide the Locale.US parameter, I get a ParseException.

How can I accomplish a correct parsing so the date provided is correct for any Local?

Here's the function:

public String parseDate (String dateraw){
        String returndate;

        try {String format = "EEE, dd MMM yyyy kk:mm:ss Z";
        SimpleDateFormat sdf = new SimpleDateFormat("EEE, dd MMM yyyy kk:mm:ss z",Locale.US);
        Date formatedDate = sdf.parse(dateraw);

        Calendar c= Calendar.getInstance();
        c.setTime(formatedDate);



        returndate=""+c.get(Calendar.DAY_OF_MONTH)+"/"+c.get(Calendar.MONTH)+"/"+c.get(Calendar.YEAR)+" "+c.get(Calendar.HOUR_OF_DAY)+":"+c.get(Calendar.MINUTE);
            return returndate;
        } catch (ParseException e) {
            e.printStackTrace();
            // TODO Auto-generated catch block
            return "NO DATE AVAILABLE";

        }
    }

Your code works fine. The date is parsed and is not timezone dependent. Try to print your current timezone or calendar timezone and see if that is correct:

        //...            
        Calendar c = Calendar.getInstance();
        c.setTime(formatedDate);
        Log.i(TAG, c.getTimeZone().getID());
        Log.i(TAG, TimeZone.getDefault().getID());
        //...

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