Mike
Mike

Reputation: 1327

Re-formatting Date object (Java)

I am currently working on a basic RSS Feed program that displays tweets given a parse-able Twitter source. What I'm currently working on is re-formatting the date. When I retrieve the pubDate it parses in the form "EEE, d MMM yyyy HH:mm:ss Z." What I want to do is re-format it such that when I display it on my GUI, it comes out as "MM/dd/yyyy HH:mm." How do I go about doing this? Here is the necessary chunk of code:

try {
    builder = factory.newDocumentBuilder();
    Document feedDocument = builder.parse(sourceListItem);
    XPathFactory xpfactory = XPathFactory.newInstance();
    XPath xpath = xpfactory.newXPath();
    String countStr = xpath.evaluate("count(/rss/channel/item)", feedDocument);
    int itemCount = Integer.parseInt(countStr);
    for(j=1; j<=itemCount; j++) {
        try {
            String title = xpath.evaluate("/rss/channel/item[" + j + "]/title", feedDocument);
            String link = xpath.evaluate("/rss/channel/item[" + j + "]/link", feedDocument);
            String date = xpath.evaluate("/rss/channel/item[" + j + "]/pubDate", feedDocument);
            DateFormat df = new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss Z");
            Calendar c = Calendar.getInstance();
            Date d = df.parse(date);
            DateFormat df2 = new SimpleDateFormat("MM/dd/yyyy HH:mm");
            String dateFormat = df2.format(d);
            c.setTime(d);
            RSSItemClass rssItem = new RSSItemClass(title, link, c);
            rssList.add(rssItem);
        } catch (ParseException e) {
            badSourceList.add(sourceListItem);
        }
    }
} catch (ParserConfigurationException e) {
    badSourceList.add(sourceListItem);
}

Upvotes: 2

Views: 5973

Answers (2)

Michał Kosmulski
Michał Kosmulski

Reputation: 10020

You have the line String dateFormat = df2.format(d); in your code but you don't use the dateFormat variable anywhere.

Upvotes: 0

Thomas
Thomas

Reputation: 88707

Since you seem to "display" the value of a Calendar object in your GUI, you don't have to format the date in the method you posted but only when the date is converted to a string in the GUI.

How this is done depends on the GUI framework you're using but most likely you need this code somewhere:

DateFormat df2 = new SimpleDateFormat("MM/dd/yyyy HH:mm");
String formattedDate = df2.format(calendar.getTime());

Where calendar is the c you pass to new RSSItemClass(title, link, c);

Upvotes: 3

Related Questions