DateTimeFormatter.ISO_INSTANT在毫秒时出现问题

时间:2016-04-05 22:42:55

标签: java

我正在使用DateTimeFormatter但是在999毫秒之后的毫秒结束时它会丢失毫秒字段。如果这个问题与java相关,请告诉我

public static void main(String[] args) throws IOException {
            // TODO Auto-generated method stub
            File file = new File("/users/test/filenamedate12.txt");

            // if file doesnt exists, then create it
            if (!file.exists()) {
                file.createNewFile();
            }
            BufferedWriter bw= null;
            FileWriter fw = new FileWriter(file.getAbsoluteFile());
            bw = new BufferedWriter(fw);
            for(int i=0;i<=1000000;i++){
            ZonedDateTime zdt = ZonedDateTime.now();
            String  content =zdt.format(DateTimeFormatter.ISO_INSTANT);


                //String content = "This is the content to write into create file";


            bw.write(content);
             bw.newLine();



            }

            bw.flush();
            bw.close();
        }

输出样本

2016-04-05T22:32:56.999Z
2016-04-05T22:32:56.999Z
2016-04-05T22:32:56.999Z
2016-04-05T22:32:56.999Z
2016-04-05T22:32:56.999Z
2016-04-05T22:32:56.999Z
2016-04-05T22:32:56.999Z
2016-04-05T22:32:56.999Z
2016-04-05T22:32:56.999Z
2016-04-05T22:32:56.999Z
2016-04-05T22:32:56.999Z
2016-04-05T22:32:56.999Z
2016-04-05T22:32:56.999Z
2016-04-05T22:32:56.999Z
2016-04-05T22:32:56.999Z
2016-04-05T22:32:56.999Z
2016-04-05T22:32:57Z
2016-04-05T22:32:57Z
2016-04-05T22:32:57Z
2016-04-05T22:32:57Z
2016-04-05T22:32:57Z
2016-04-05T22:32:57Z
2016-04-05T22:32:57Z
2016-04-05T22:32:57Z

1 个答案:

答案 0 :(得分:1)

不,这是故意的。来自DateTimeFormatter.ISO_INSTANT的javadoc:

  

纳秒级根据需要输出零,三,六或九位数字。

换句话说,为了简洁,删除0后的多余.

源代码显示:

ISO_INSTANT = new DateTimeFormatterBuilder()
                .parseCaseInsensitive()
                .appendInstant()
                .toFormatter(ResolverStyle.STRICT, null);

appendInstant方法负责此行为。该方法的文档也提到了它。