我正在嘗試使用Java的SimpleDateFormat
將字符串轉換爲正確的日期格式。由於某些原因,它不適用於「Mar」,「May」,「Oct」和「Dec」等某些月份。有人能幫助我嗎?它在其他所有月份都能正常工作。將字符串轉換爲格式化日期
import java.sql.Date;
import java.text.SimpleDateFormat;
import com.sun.org.apache.xerces.internal.impl.xpath.regex.ParseException;
public class test {
public static void main(String args[]) throws java.text.ParseException {
try {
SimpleDateFormat parse = new SimpleDateFormat("dd. MMM yyyy hh:mm:ss");
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//why this doesn't work with certain months like Mar, May, Oct, and Dec? otherwise it works fine
String dateTime = "01. Jun 2010 15:30:32";
//String dateTime = "07. Mar 2011 15:20:10";
//String dateTime = "07. May 2011 15:20:10";
//String dateTime = "07. Oct 2011 15:20:10";
//String dateTime = "07. Dec 2011 15:20:10";
java.util.Date parsed =parse.parse(dateTime);
System.out.println("formatted: " + formatter.format(parsed));
} catch(ParseException e) {
System.out.println("Caught " + e);
}
}
}
我試着運行你的代碼,它爲我完美工作。你面臨的問題是什麼?順便說一句,你應該抓住'java.text.ParseException'而不是'com.sun.org.apache.xerces.internal.impl.xpath.regex.ParseException' – Nishan 2011-04-07 13:05:44
添加'com.sun。*'包來忽略列表中的內容IDE自動建議列表。 – BalusC 2011-04-07 13:24:08