例如,我正在尝试解析 SQL 日期字符串 (ISO 9075),它使用微秒(!)而不是毫秒
2010-11-22 08:08:08.123456
但是,SimpleDateFormat 拒绝识别诸如“yyyy-MM-dd HH:mm:ss.SSSSSS”之类的模式,并且“yyyy-MM-dd HH:mm:ss.SSS”也不起作用。
我使用的代码看起来像这样:
String dateString = "2010-11-22 08:08:08.123456";
String pattern = "yyyy-MM-dd HH:mm:ss.SSSSSS";
try
{
format = new SimpleDateFormat(pattern);
format.setLenient(false);
position.setIndex(0);
Date date1 = format.parse(dateString, position);
System.out.println("Date 1: " + date1);
Date date2 = format.parse(dateString);
System.out.println("Date 2: " + date1);
}
catch (Exception e) // Should not happen
{
e.printStackTrace();
}
无论我使用两种模式(“.SSS”或“.SSSSSS”)中的哪一种,date1 都会被打印为 null
,而 date2 会导致解析异常 (java.text.ParseException: Unparseable date )。
最佳答案
也许在解析日期之前将日期字符串中剩余的小数部分切掉?我有以下内容
String dateString = "2010-11-22 08:08:08.123456";
String fraction = dateString.substring(dateString.length() - 3);
String formatString = dateString.substring(0, dateString.length() - 3);
String pattern = "yyyy-MM-dd HH:mm:ss.SSS";
ParsePosition position = new ParsePosition(0);
try
{
SimpleDateFormat format = new SimpleDateFormat(pattern);
format.setLenient(false);
position.setIndex(0);
Date date1 = format.parse(formatString, position);
System.out.println("Date 1: " + date1);
System.out.println("Date 1 fraction: " + fraction);
Date date2 = format.parse(formatString);
System.out.println("Date 2: " + date2);
System.out.println("Date 2 fraction: " + fraction);
}
catch (Exception e) // Should not happen
{
e.printStackTrace();
}
这允许日期解析到毫秒精度,同时您仍然保留分数微部分。
关于SQL 日期的 Java 日期模式 (ISO 9075),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8236009/