为什么 Java 时间戳解析在毫秒部分加前缀 0?

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;   

它给了我以下输出:

For Input String: 00:17.20 -> Parsed date 00:17.20-> will print as to  00:00:17,020

但是我想解析这样的字符串 00:00:17,200

我错过了什么?

格式化程序将 .20 解释为 20 毫秒,而不是 .2 秒(即 200 毫秒)。要解决此问题,您只需在字符串中添加一个零即可。

d = formatter.parse(lrcTime + "0");

有一个歧义在较新的日期时间得到改善 类:

SimpleDateFormat

  • S = 毫秒

    SS 为 20 表示 20 毫秒,因此 SSS 将为 020 毫秒。

较新的DateTimeFormatter

  • S = 秒的小数部分。

    将给出 SSS = 200 毫秒

新解释背后的基本原理是,对于微秒和纳秒,2 毫秒 ,2 并不真正适合 ,SSSSSS 之类的东西 - 正如您所说。