简体   繁体   English

Java DateFormat,精度为2毫秒

[英]Java DateFormat for 2 millisecond precision

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. 我有一个问题,试图让DateFormat库给我一个字符串,日期要格式化为2毫秒而不是通常的3.我意识到这更像是在厘秒线上,但是afaik Java不支持。

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 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 根据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) . 我将仅为SSS使用单独的格式并调用substring(0, 2)

我无法推断出问题发生的原因,但在用yoda替换日期格式后,生成的时间字符串具有正确的秒数[仅为2]。

I would include Joda Time and use something like: 我会包括Joda Time并使用类似的东西:

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. 如果你不想要额外的依赖,我认为从.format(...)结果字符串是唯一的方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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