I have time stamp as string "2013-01-28 11:01:56.9". Here 56.9 seconds are mentioned.
.9 seconds = 900 milliseconds
we can say it's 9 deci-seconds or 90 centi-seconds
But in java...
String string = "2013-01-28 11:01:56.9";
String pattern = "yyyy-MM-dd hh:mm:ss.S";
SimpleDateFormat formatter = new SimpleDateFormat(pattern);
Date date = formatter.parse(string);
System.out.println(date.getTime());
Output is : 1359388916009
Here 9 is parsed as 009 milliseconds because "S" (Capital-S) is used for milliseconds.
Similarly if .95 seconds are provided as and parsed with "SS" pattern, it gives "095" milliseconds instead of "950" milliseconds.
Why java does not provide pattern to parse/format deci-seconds and centi-seconds to make things easier?
What is the decent way to do so?
解决方案
1) Nobody knows why Java does not provide pattern to parse/format deci-seconds and centi-seconds. But I personally suspect, that though your case is very interesting, it is a very particular case of formatting.
It is hard to imagine such convenient formatting style, which will allow to distinguish case, when . symbol is delimiter between integer and float parts, and when it is just delimiter between date's parts.
2) About decent way. It seems to me, that this simple preprocessing should help you:
public static String preprocess(String date) {
int pIndex = date.lastIndexOf(".") + 1;
String millis = date.substring(pIndex);
for (int i = millis.length(); i < 3; i++)
millis += "0";
return date.substring(0, pIndex) + millis;
}
UPD: It could be written more simple:
public static String preprocess(String date) {
String millis = date.substring(date.lastIndexOf(".") + 1);
for (int i = millis.length(); i < 3; i++)
date += "0";
return date;
}