Java 8 LocalDateTime-如何在字符串转换中保留.000毫秒 [英] Java 8 LocalDateTime - How to keep .000 milliseconds in String conversion

查看:382
本文介绍了Java 8 LocalDateTime-如何在字符串转换中保留.000毫秒的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个通过 String 接收的时间戳,格式如下:

I have a timestamp that I receive via a String in the following format:

2016-10-17T12:42:04.000

2016-10-17T12:42:04.000

我将其转换为 LocalDateTime ,以通过以下几行为其添加几天(然后返回至 String ):

I am converting it to a LocalDateTime to add some days to it (then back to a String) via the following line:

String _120daysLater = LocalDateTime.parse("2016-10-17T12:42:04.000",
    DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS")).minusDays(120).toString());

但是,我注意到它返回的响应下降了 .000 毫秒.

However, I noticed that the response it gives back drops the .000 milliseconds.

我不确定确保保留正确模式的最干净方法.现在,我只添加一个毫秒,并且可能有一种方法可以将旧的 SimpleDateFormat 并入其中,但我希望有一个更好的方法.

I'm not sure the cleanest way to ensure that the exact pattern is preserved. For now I'm just adding a single millisecond, and there's probably a way to incorporate the old SimpleDateFormat into it, but I was hoping there's an even better way.

推荐答案

LocalDateTime::toString omits parts if zero:

使用的格式将是最短的格式,用于输出被省略部分隐含为零的时间的完整值.

The format used will be the shortest that outputs the full value of the time where the omitted parts are implied to be zero.

使用

这篇关于Java 8 LocalDateTime-如何在字符串转换中保留.000毫秒的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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