5

I'm having a problem with trying to get the DateFormat library to give me a String with the date to be formatted with 2 millisecond places instead of the usual 3. I realize this is more along the line of centi-seconds, but afaik Java doesn't support that.

Here is some code to show the problem I am having. I would expect it to output to two milliseconds, but it outputs 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 digit I don't want, but I was hoping there would be a cleaner way to achieve this. Does anyone know how to get this to work, or why it is not working?

rogerdpack
  • 62,887
  • 36
  • 269
  • 388
Lithium
  • 5,102
  • 2
  • 22
  • 34

3 Answers3

6

Sorry. Acording to the javadoc

the number of letters for number components are ignored except it's needed to separate two adjacent fields

...so I don't think there's a direct way to do it.

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

helios
  • 13,574
  • 2
  • 45
  • 55
  • Thanks, I didn't think about having a separate format for the milliseconds. – Lithium Feb 20 '12 at 16:39
  • 2
    Maybe less complicated to do the whole thing in one go, but without the Zulu time indicator. Then just trim off the last character and add on the Z. – clstrfsck Feb 20 '12 at 16:51
0

I haven't been able to deduce why is the problem happening, but after replacing date format with yoda, the generated time string had correct number number of seconds [ only 2].

bbaja42
  • 2,099
  • 18
  • 34
  • 1
    I think it's only the method contract. When you say S it's the miliseconds from 1 to 3 digits. SS is ms from 2 to 3 digits. SSS is always with 3 digits. Maybe yoda has another contract. – helios Feb 20 '12 at 16:27
  • @helios, you are right. For SS, it will display only 2 digits only if 3rd digit is 0. – bbaja42 Feb 20 '12 at 16:32
0

I would include 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 don't want the additional dependency, I think twiddling the result string from .format(...) is the only way.

clstrfsck
  • 14,715
  • 4
  • 44
  • 59