简体   繁体   中英

SimpleDateFormat format removes leading zero from milliseconds

I'm having difficulties formating milliseconds with SimpleDateFormat. I'm trying to get accurate millisecond output with pattern "SS", but when millisecond starts with zero SimpleDateFormat.format() will remove leading zero and return remaining digits.

For example I'm expecting to get output of "08" but instead I get "87" from time 02:20:48.087 with format pattern "SS" or "S".

In javadoc it's stated that two letter pattern outputs are interpreted as numbers but same problem also occurs with one S letter.

SimpleDateFormat test = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SS");
Calendar testCalendar = Calendar.getInstance();
long unixtime = 435457248087L; // 1983-10-20 02:20:48.087
testCalendar.setTimeInMillis(unixtime);

String output = test.format(testCalendar.getTime());
System.out.println(output); // outputs 1983-10-20 02:20:48.87, not xxx.08

This is of course easily fixed with using "SSS" pattern, but I'm just curious is this a bug or what's the catch with this one.

SS is just "the number of milliseconds, 0-padded if necessary to give a 2-digit result". So it looks like it's behaving as expected by the documentation.

Personally I think it would be more sensible if it were specified (and implemented) to give 08 as the fraction of a second to 2 decimal places - that's unfortunately not how it works.

I don't think there's any way of specifying "fraction of a second to 2 decimal places" using SimpleDateFormat .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM