Java DateFormat的精度为2毫秒 [英] Java DateFormat for 2 millisecond precision

查看:90
本文介绍了Java DateFormat的精度为2毫秒的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在尝试获取DateFormat库以给我一个带有要格式化的日期而不是通常的3毫秒的日期的字符串时遇到了问题,我意识到这更多的是厘秒,但是afaik Java不支持。

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);
}}

输出:

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?

推荐答案

对不起。根据 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.

我只会使用单独的格式 SSS 并调用 substring(0,2)

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

这篇关于Java DateFormat的精度为2毫秒的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆