[英]Why Java timestamp parsing is prefixing 0 in millisecond part?
final String OLD_FORMAT = "mm:ss.SS";
final String TARGET_FORMAT = "HH:mm:ss,SSS";
String timeInputStr="00:17.20"; // input is always in mm.ss.SS m--> minutes, ss-> seconds , and SSS is decimal fraction of seconds always , not actual milliseconds
String timeOutputStr="";
Date d=new Date();
DateFormat formatter= new SimpleDateFormat(OLD_FORMAT);
DateFormat nformatter= new SimpleDateFormat(TARGET_FORMAT);
try{
d = formatter.parse(timeInputStr);
}
catch (ParseException e){
System.out.println("Can't Parse date "+d + " from: " +lrcTime );
}
timeInputStr=nformatter.format(d);
System.out.println( "For Input String: " + lrcTime + " -> Parsed date "+ formatter.format(d) + "-> will print as to " + timeInputStr);
return timeOutputStr;
It's giving me the following output:它给了我以下输出:
For Input String: 00:17.20 -> Parsed date 00:17.20-> will print as to 00:00:17,020
But I want to parse such string as 00:00:17,200
但我想解析这样的字符串
00:00:17,200
What am I missing?我错过了什么?
There is an ambiguity that is improved in the newer date time classes:在较新的日期时间类中改进了歧义:
The old SimpleDateFormat旧的SimpleDateFormat
S = millisecond S = 毫秒
SS with 20 means 20 ms, hence SSS will be 020 ms. SS 为 20 表示 20 ms,因此 SSS 将为 020 ms。
The newer DateTimeFormatter较新的DateTimeFormatter
S = fraction of second. S = 秒的分数。
Will give SSS = 200 ms会给 SSS = 200 ms
The rationale behind the new interpretation is that with microseconds and nanoseconds a 2 ms as ,2
does not really fit with things like ,SSSSSS
- as you remarked.新解释背后的基本原理是,对于微秒和纳秒,2 ms as
,2
并不真正适合,SSSSSS
- 正如您所说的那样。
The formatter interprets the .20
as 20 milliseconds, not .2 seconds (which would be 200ms).格式化程序将
.20
解释为 20 毫秒,而不是 0.2 秒(即 200 毫秒)。 To resolve this issue, you can simply add a zero to your String.要解决此问题,您只需在字符串中添加一个零即可。
d = formatter.parse(lrcTime + "0");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.