Search code examples
javatimeapache-commons

FastDateFormat HHmmssS behaviour like HHmmSSS


The source FastDateFormat.getInstance("HHmmssS").format(Calendar.getInstance()); returns a string in the format "HHmmssSSS" e.g. 152712599 instead expected 1527125.

The package and version are "package org.apache.commons.lang3.time; @version $Id: FastDateFormat.java 1591488 2014-04-30 21:49:35Z".

A workaround will be provided in the solution below.


Solution

  • Actually what you want are deciseconds, not milliseconds, but you are right, there is no support for that (yet?).

    Beware that formatting it with a single 'S' might give you only the actual millisecond, so you need to use the format string "HHmmssSSS". The substring itself should then be of length "HHmmssS".length().

    So your actual workaround/solution should rather be:

    public static <Format> String HHMMssS(final Format calendar) {
      final String HHmmssS = "HHmmssSSS";
      return FastDateFormat.getInstance(HHmmssS).format(calendar).substring(0, "HHmmssS".length());
    }
    

    A related question (regarding parsing): Deci and Centi Seconds parsing in java