日付/日時のさまざまな文字列表現をタイムスタンプオブジェクトに変換する次のコードがあります。
public class GeneralMethods {
public static String[] formats = {"dd/mm/yyyy","mm/dd/yyyy hh:mm:ss","E MMM dd HH:mm:ss zzz yyyy"};
/**
* a method to return timestamp object from string date in the formats
* {"dd/mm/yyyy HH:mm:ss","E MMM dd HH:mm:ss zzz yyyy","dd/mm/yyyy"}
* @param date: the date to format in string representation
* @return timestamp object
*/
public static Timestamp timestampFormat(String date)
{
Date dateObj = new Date();
for(String format: formats)
{
try
{
dateObj = new SimpleDateFormat(format).parse(date);
System.out.println(dateObj.toString()); // for tracking
}catch (ParseException e)
{
}
}
return new Timestamp(dateObj.getTime());
}
// testing
public static void main (String args[])
{
System.out.println(timestampFormat("05/31/2011 21:37:35"));
}
}
このコードからの出力は次のとおりです。
Wed Jan 05 00:31:00 GMT 2011
Mon Jan 31 21:37:35 GMT 2011
2011-01-31 21:37:35.0
ご覧のとおり、出力の月は入力05/31/201121:37:35に対して間違っています。これはどのように起こっていますか?