其他人已经回答了原因。这里有一个出发点,以避开它:
import java.text.*;
import java.util.Date;
public class DatePercentage {
private final SimpleDateFormat dateFmt = new SimpleDateFormat(
"yyyy-MM-dd HH:mm:ss");
private final DecimalFormat decFmt = new DecimalFormat();
public Date parse(String text) throws ParseException {
ParsePosition pos = new ParsePosition(0);
Date d = dateFmt.parse(text, pos);
if (d == null) {
throw new ParseException("Could not parse " + text + ": " + pos,
pos.getErrorIndex());
} else if (pos.getIndex() < text.length()) {
Number dec = decFmt.parse(text, pos); // % milliseceonds
double pct = dec == null ? 0 : dec.doubleValue();
if (0 < pct && pct < 1) {
long moreMillis = Math.round(pct * 1000);
d = new Date(d.getTime() + moreMillis);
}
}
return d;
}
public static void main(String[] args) throws ParseException {
String date = "2011-12-31 07:11:01";
String [] millis = {"", ".5", ".50", ".500", ".5001",
".051", ".5009", "garbage"};
DatePercentage dp = new DatePercentage();
for (int i = 0; i < millis.length; i++) {
String str = date + millis[i];
System.out.format("%2s: %26s -> %tQ%n", i+1, str, dp.parse(str));
}
}
}
输出:
1: 2011-12-31 07:11:01 -> 1325333461000
2: 2011-12-31 07:11:01.5 -> 1325333461500
3: 2011-12-31 07:11:01.50 -> 1325333461500
4: 2011-12-31 07:11:01.500 -> 1325333461500
5: 2011-12-31 07:11:01.5001 -> 1325333461500
6: 2011-12-31 07:11:01.051 -> 1325333461051
7: 2011-12-31 07:11:01.5009 -> 1325333461501
8: 2011-12-31 07:11:01garbage -> 1325333461000
这是行不通的。它给出了与'.SS'相同的结果。 – user219882 2012-01-07 12:16:09
无论你使用什么解析's'或'ss.SSS',它只会用于格式化。请参阅我在答案 – Robin 2012-01-07 12:28:21
@Tomas中引用的javadoc部分。当我告诉你用零填充字符串以确保总是有三位数字时,你错过了这个部分。 – 2012-01-07 17:15:46