2012-05-31 129 views
2

我目前正在研究一个基本的RSS源程序,该程序显示给出可解析的Twitter源的推文。我目前正在处理的是重新格式化日期。当我检索pubDate时,它将以“EEE,d MMM yyyy HH:mm:ss Z”的形式进行解析。我想要做的是重新格式化,当我在GUI上显示它时,它会显示为“MM/dd/yyyy HH:mm”。我如何去做这件事?这里是代码的必要块:重新格式化日期对象(Java)

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); 
} 
+0

哪里的问题/问题?看起来你已经有了一个解决方案,虽然你没有使用格式化的日期字符串'dateFormat'。 – Thomas

+0

我的日期d'解析表单“EEE,d MMM yyyy HH:mm:ss Z”,但是当我在GUI中显示日期时,我不希望它以这种格式出现,我希望它出来格式为“MM/dd/yyyy HH:mm”。对困惑感到抱歉。 – Mike

回答

3

由于您似乎在GUI中“显示”了Calendar对象的值,因此您不必在发布的方法中格式化日期,而只需在GUI中将日期转换为字符串时进行格式化。

如何做到这一点取决于你使用的GUI框架,但很可能需要验证码的地方:

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

哪里calendarc传递给new RSSItemClass(title, link, c);

+0

谢谢!它现在有效! – Mike

0

你在你的代码行String dateFormat = df2.format(d);但你不使用任何地方的dateFormat变量。

+0

当我尝试解析字符串'dateFormat'时,我没有得到我想要的“MM/dd/yyyy HH:mm”格式。 – Mike

+0

@ michal-kosmulski参数无误。 'SimpleDateFormat'是一个'DateFormat',它有'format(Date)'方法。 – dogbane

+0

另外,那个接受三个参数的'format()'方法是用于SimpleDateFormat,而我正在使用DateFormat。 – Mike