簡體   English   中英

日期格式設置不正確

[英]Date formatting is not formatting correctly

我不知道為什么這會返回CDT 2014年7月2日星期三18:21:27而不是2014年7月2日下午6:21

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;

}
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進行格式化,在這里,您僅將一個日期的參考分配給另一個日期,但是一個日期的格式不會影響另一個日期每當您要使用pubDate時,都將其應用於this.pubDate

您可以聲明通用格式(類級別對象),並在需要顯示日期時在程序中使用它。

如果要打印所需的格式,則必須使用String表示日期,否則,日期類型將始終打印此格式“ dow mon dd hh:mm:ss zzz yyyy”

由於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 ,則需要使用newFormat

 // As a String
System.out.println(newFormat.format(dateFormat.parse(pubDate)));
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));

}

在下面使用更正的代碼:

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));

}

試試這個,創建您的自定義日期類

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());

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM