我有以下代码将日期/日期时间的不同字符串表示形式转换为时间戳对象:
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/2011 21:37:35 是错误的。这是怎么回事?