java seconds,Deci和Centi Seconds在java中解析

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;

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值