8 月 31 日星期五的日期格式异常 00:00:00 CAT 2012

Date format exception for Fri Aug 31 00:00:00 CAT 2012

我试图使用 EEE MMM dd yyyy hh:mm:ss zzzz yyyy 格式设置日期 Fri Aug 31 00:00:00 CAT 2012 的格式,但我得到 Unparseable date: "Fri Aug 31 00:00:00 CAT 2012"

我正在使用此代码

String DATE_FORMAT = "EEE MMM dd yyyy hh:mm:ss zzzz yyyy"; 
SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT); 
Date date = sdf.parse(myObj.getDate().toString());

我是不是漏掉了什么?

您的格式中有一个额外的 yyyy。 试试这个:

SimpleDateFormat sdf = new SimpleDateFormat("EEE MMM dd hh:mm:ss zzzz yyyy");
Date date = sdf.parse("Fri Aug 31 00:00:00 CAT 2012");

你在那里有两次年份标记:

String DATE_FORMAT = "EEE MMM dd yyyy hh:mm:ss zzzz yyyy"; 
                                 ^ remove this one.

你已经有了一个 Date-object,想通过 toString() 使用它的标准输出格式化它并再次将它解析为一个 Date-object,这很奇怪。这个过程甚至丢失了原始 Date-object 的毫秒部分(myObj.getDate())。无论如何,进行解析的正确格式模式是:

EEE MMM dd HH:mm:ss zzz yyyy

并且不要忘记将 SimpleDateFormat-对象的语言环境设置为英语。请注意,您有两次 yyyy 部分并且还使用了 "h"(am/pm 的小时)而不是 "H"(一天中的小时)。另请参阅 class java.util.Date:

的源代码
/**
 * Converts this <code>Date</code> object to a <code>String</code>
 * of the form:
 * <blockquote><pre>
 * dow mon dd hh:mm:ss zzz yyyy</pre></blockquote>
 * where:<ul>
 * <li><tt>dow</tt> is the day of the week (<tt>Sun, Mon, Tue, Wed,
 *     Thu, Fri, Sat</tt>).
 * <li><tt>mon</tt> is the month (<tt>Jan, Feb, Mar, Apr, May, Jun,
 *     Jul, Aug, Sep, Oct, Nov, Dec</tt>).
 * <li><tt>dd</tt> is the day of the month (<tt>01</tt> through
 *     <tt>31</tt>), as two decimal digits.
 * <li><tt>hh</tt> is the hour of the day (<tt>00</tt> through
 *     <tt>23</tt>), as two decimal digits.
 * <li><tt>mm</tt> is the minute within the hour (<tt>00</tt> through
 *     <tt>59</tt>), as two decimal digits.
 * <li><tt>ss</tt> is the second within the minute (<tt>00</tt> through
 *     <tt>61</tt>, as two decimal digits.
 * <li><tt>zzz</tt> is the time zone (and may reflect daylight saving
 *     time). Standard time zone abbreviations include those
 *     recognized by the method <tt>parse</tt>. If time zone
 *     information is not available, then <tt>zzz</tt> is empty -
 *     that is, it consists of no characters at all.
 * <li><tt>yyyy</tt> is the year, as four decimal digits.
 * </ul>
 *
 * @return  a string representation of this date.
 * @see     java.util.Date#toLocaleString()
 * @see     java.util.Date#toGMTString()
 */
public String toString() {
    // "EEE MMM dd HH:mm:ss zzz yyyy";