日期格式未正确格式化

时间:2014-07-08 04:07:14

标签: java android date simpledateformat

我无法弄清楚为什么会这样 周三7月2日18:21:27 CDT 2014 代替 07/02/14 6:21 pm

pubdate = Mon, 30 Jun 2014 22:37:15 +0000

public void setPubDate(String pubDate) {

    SimpleDateFormat dateFormat = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss Z", Locale.ENGLISH);
    long x = dateFormat.parse(pubDate).getTime();
    Date date = new Date(x);
    SimpleDateFormat newFormat = new SimpleDateFormat("MM/dd/yy H:mm aa");
    newFormat.format(dateFormat.parse(pubDate));
    this.pubDate = date;

}

6 个答案:

答案 0 :(得分:1)

this.pubDate = date;//Assign the reference of date Object
//this.pubDate will have value of date NOT Format :)

但是这里格式不会传递给pubDate,因为它会保持不变。 如果您想让pubDate具有dd/Mm/yyyy aa格式,您还必须格式化pubDate此处,您只需将参考从一个日期指定给其他日期,但在一个日期的表单赢得&#39 ; t;如果您想使用this.pubDate,则必须将其应用于pubDate

您可以声明通用格式(类级别对象),并在您希望显示日期时在程序中使用它。

答案 1 :(得分:1)

如果要打印所需的格式,则必须使用String来表示日期,否则,日期类型将始终打印此格式&#34; dow mon dd hh:mm:ss zzz yyyy&#34; < / p>

答案 2 :(得分:0)

因为Date每个Javadoc都有toString()

  

将此Date对象转换为以下形式的字符串:

dow mon dd hh:mm:ss zzz yyyy
     

其中:

dow is the day of the week (Sun, Mon, Tue, Wed, Thu, Fri, Sat).
mon is the month (Jan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec).
dd is the day of the month (01 through 31), as two decimal digits.
hh is the hour of the day (00 through 23), as two decimal digits.
mm is the minute within the hour (00 through 59), as two decimal digits.
ss is the second within the minute (00 through 61, as two decimal digits.
zzz is the time zone (and may reflect daylight saving time). Standard time zone 
    abbreviations include those recognized by the method parse. If time zone 
    information is not available, then zzz is empty - that is, it consists of no 
    characters at all.
yyyy is the year, as four decimal digits. 

如果您想偏离这一点,则需要newFormat -

 // As a String
System.out.println(newFormat.format(dateFormat.parse(pubDate)));

答案 3 :(得分:0)

public void setPubDate(String pubDate) {

  SimpleDateFormat dateFormat = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss Z", Locale.ENGLISH);
  long x = dateFormat.parse(pubDate).getTime();
  Date date = new Date(x);
  SimpleDateFormat newFormat = new SimpleDateFormat("MM/dd/yy H:mm aa");
  return newFormat.format(dateFormat.parse(pubDate));

}

答案 4 :(得分:0)

使用以下更正的代码:

public void setPubDate(String pubDate) {

SimpleDateFormat dateFormat = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss Z", Locale.ENGLISH);
long x = dateFormat.parse(pubDate).getTime();
Date date = new Date(x);
SimpleDateFormat newFormat = new SimpleDateFormat("MM/dd/yy H:mm aa");
System.out.println("Formatted date is ="+ newFormat.format(x));

}

答案 5 :(得分:0)

试试这个,创建自定义日期类

public class MyDate extends Date
{
    @Override
    public String toString() {
        SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yy hh:mm aa");
        return dateFormat.format(new Date());           
    }
}

然后打印像

这样的对象

System.out.println(new MyDate());

相关问题