Java DateFormat for 2 millisecond precision

I'm having trouble trying to get the DateFormat library to give me a String with a date that will be formatted with 2 milliseconds instead of the usual 3. I understand that this is more on the line of cent-seconds, but afaik Java does not support this.

Here is some code to show the problem I am facing. I expect it to come out before two milliseconds, but it will output three.

public class MilliSeconds { private static final String DATE_FORMAT_2MS_Digits = "yyyy-MM-dd'T'HH:mm:ss.SS'Z'"; private static DateFormat dateFormat2MsDigits = new SimpleDateFormat(DATE_FORMAT_2MS_Digits); public static void main( String[] args ){ long milliseconds = 123456789123l; System.out.println(formatDate2MsDigits(new Date(milliseconds))); } public static String formatDate2MsDigits(Date date) { dateFormat2MsDigits.setCalendar(Calendar.getInstance(new SimpleTimeZone(0, "GMT"))); return dateFormat2MsDigits.format(date); }} 

outputs:

1973-11-29T21: 33: 09.123Z

I could just parse the resulting string and remove the number I don't want, but I was hoping there would be a cleaner way for this. Does anyone know how to make this work, or why it is not working?

+4
source share
3 answers

Unfortunately. According to javadoc

the number of letters for numeric components is ignored, except for the need to separate two adjacent fields

... so I don’t think there is a direct way to do this.

I would use a separate format for SSS only and call substring(0, 2) .

+3
source

I could not understand why the problem occurs, but after replacing the yoda date format, the generated time string was the correct number of seconds [only 2].

0
source

I would enable Joda Time and use something like:

 private static final String DATE_FORMAT_2MS_FMT = "yyyy-MM-dd'T'HH:mm:ss.SS'Z'"; private static final DateTimeFormatter DATE_FORMAT_2MS_DIGITS = DateTimeFormat .forPattern(DATE_FORMAT_2MS_FMT).withZoneUTC(); public static String formatDate2MsDigits(Date date) { return DATE_FORMAT_2MS_DIGITS.print(date.getTime()); } 

If you do not need an additional dependency, I think that the only way can be considered is the result string from .format(...) .

0
source

Source: https://habr.com/ru/post/1397459/


All Articles