如何在Java8中从LocalTime中删除毫秒
使用java.time框架,我希望以如何在Java8中从LocalTime中删除毫秒,java,rounding,datetime-format,java-time,localtime,Java,Rounding,Datetime Format,Java Time,Localtime,使用java.time框架,我希望以hh:mm:ss格式打印时间,但是LocalTime.now()以hh:mm:ss,nnn格式给出时间。我尝试使用DateTimeFormatter: DateTimeFormatter formatter = DateTimeFormatter.ISO_LOCAL_TIME; LocalTime time = LocalTime.now(); String f = formatter.format(time); System.out.println(f);
hh:mm:ss
格式打印时间,但是LocalTime.now()
以hh:mm:ss,nnn
格式给出时间。我尝试使用DateTimeFormatter
:
DateTimeFormatter formatter = DateTimeFormatter.ISO_LOCAL_TIME;
LocalTime time = LocalTime.now();
String f = formatter.format(time);
System.out.println(f);
结果是:
22:53:51.894
如何从时间中删除毫秒?尝试使用此处定义的模式: 例如:
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy MM dd HH. mm. ss");
String text = date.toString(formatter);
只需显式创建
DateTimeFormatter
:
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("HH:mm:ss", Locale.US);
LocalTime time = LocalTime.now();
String f = formatter.format(time);
System.out.println(f);
(我更喜欢显式地使用US语言环境,以明确我不需要任何来自默认格式语言环境的内容。)在第一行中使用此选项
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("HH:mm:ss");
只需在字符串上使用正则表达式即可:
String f = formatter.format(time).replaceAll("\\.[^.]*", "");
这将删除(用空白替换)最后一个点和之后的所有内容。编辑:我应该补充一点,这些都是纳秒而不是毫秒 我觉得这些答案并没有真正回答使用Java8SE日期和时间API的问题。我相信截断法就是这里的解决方案
LocalDateTime now = LocalDateTime.now();
System.out.println("Pre-Truncate: " + now);
DateTimeFormatter dtf = DateTimeFormatter.ISO_DATE_TIME;
System.out.println("Post-Truncate: " + now.truncatedTo(ChronoUnit.SECONDS).format(dtf));
输出:
Pre-Truncate: 2015-10-07T16:40:58.349
Post-Truncate: 2015-10-07T16:40:58
Pre-Truncate: 2015-10-07T16:38:53.900-06:00[America/Denver]
Post-Truncate: 2015-10-07T16:38:53-06:00
或者,如果使用时区:
LocalDateTime now = LocalDateTime.now();
ZonedDateTime zoned = now.atZone(ZoneId.of("America/Denver"));
System.out.println("Pre-Truncate: " + zoned);
DateTimeFormatter dtf = DateTimeFormatter.ISO_OFFSET_DATE_TIME;
System.out.println("Post-Truncate: " + zoned.truncatedTo(ChronoUnit.SECONDS).format(dtf));
输出:
Pre-Truncate: 2015-10-07T16:40:58.349
Post-Truncate: 2015-10-07T16:40:58
Pre-Truncate: 2015-10-07T16:38:53.900-06:00[America/Denver]
Post-Truncate: 2015-10-07T16:38:53-06:00
减至分钟:
localTime.truncatedTo(ChronoUnit.MINUTES);
切换到秒:
localTime.truncatedTo(ChronoUnit.SECONDS);
例如:
LocalTime.now().truncatedTo(ChronoUnit.SECONDS).format(DateTimeFormatter.ISO_LOCAL_TIME)
输出
15:07:25
使用不同的格式化程序?在您的示例中没有纳秒,即使显示了这样的精度:在大多数操作系统中,低于1ms的时间精度没有意义/实际上是不可能的,您得到的只是一些随机噪声,用数字表示。你可以数处理器的滴答声,不过…我觉得这更像是一个hack@Shervin为什么是“黑客”?这是一个格式化问题,有一个格式化解决方案。在某种程度上,它比编写您自己的格式模式要好,因为您不需要了解任何有关模式的信息,也不需要知道如何编写一个格式模式来实现此功能。谢谢!我添加了一个示例来说明格式化程序将支持截断,这很好,而且它在ZoneDateTime
中的工作方式也一样。这让我很困惑,因为我习惯于对格式化程序对象调用parse,而不是对我想要的对象类型调用静态解析方法。谢谢