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?
解决方案
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).