0

尝试格式化日期并将其放入 Android Studio 中的 TextView 中

格林威治标准时间 2016 年 2 月 29 日星期一 22:31:00

2016-02-29 22:31:00

在我的 Genymotion Google Nexus 5、三星 Galaxy S5 等设备中,它看起来很完美。当我在真正的手机(不仅仅是一个)上运行此应用程序时,日期为空的 TextView 为空:getFormatPubDate 抛出 ParseException,其中“日期不可解析”

 date = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z").parse(pubDate);

pubDate 变量中的日期正确且不为空。

// strings.xml
    <string name="data_time_format">yyyy-MM-dd HH:mm:ss</string>

// someClass.java
    public String getFormatPubDate(String format){
                try {
                Date date = null;
                    date = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z").parse(pubDate);
                    return new SimpleDateFormat(format).format(date);
                } catch (ParseException e) {
                    e.printStackTrace();
                }
                return pubDate;
            }

// someActivity.java    
viewHolder.timePublishedTextView.setText(cachedNews.getFormatPubDate(activity.getResources().getString(R.string.data_time_format)));

PS 我使用 HH(24 小时)格式,但时间不正确。模拟器示例 - 2016 年 2 月 29 日星期一 23:01:00 GMT 格式为 2016-02-29 18:01:00

4

1 回答 1

0
 //This is original date format
 String date = "Mon, 29 Feb 2016 22:31:00";

 SimpleDateFormat sdf = new SimpleDateFormat("EE, dd MMM yyyy HH:mm:ss",
            Locale.ENGLISH);

 //This is new date format
 SimpleDateFormat print = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

 Date parsedDate = null;

 try 
 {
     parsedDate = sdf.parse(date);
 } catch (ParseException e) {
     e.printStackTrace();
 }

 String text = print.format(parsedDate);
于 2016-03-01T06:58:17.583 回答