如何在Java 8中从LocalTime中去除毫秒

37

使用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);

结果:

22:53:51.894

如何去除时间中的毫秒?


使用不同的格式化程序? - markspace
1
你的示例中没有纳秒,即使有这样的精度显示:在大多数操作系统中,低于1毫秒的时间精度是没有意义的/实际上是不可能的,你得到的只是一些随机噪声,用数字表示。但你可以计算处理器时钟周期... - specializt
6个回答

73

编辑:我应该补充说明这些是纳秒而不是毫秒。

我觉得这些答案并没有真正使用Java 8 SE的日期和时间API来回答问题,我相信truncatedTo方法是解决方案。

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

或者,如果使用时区:

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:38:53.900-06:00[America/Denver]
Post-Truncate: 2015-10-07T16:38:53-06:00    

这让我感到困惑,因为我习惯于在格式化对象上调用解析方法,而不是在我想要的对象类型的静态解析方法上。谢谢! - Sam Barnum

41

剪辑到分钟:

 localTime.truncatedTo(ChronoUnit.MINUTES);

剪切到秒数:

localTime.truncatedTo(ChronoUnit.SECONDS);
例子:
import java.time.LocalTime;
import java.time.temporal.ChronoUnit;

LocalTime.now()
  .truncatedTo(ChronoUnit.SECONDS)
  .format(DateTimeFormatter.ISO_LOCAL_TIME);

输出 15:07:25


谢谢!我添加了一个示例来展示格式化程序将遵守截断,这很棒,并且对于“ZonedDateTime”也是一样的。 - Hugues M.

11

只需明确创建DateTimeFormatter:

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("HH:mm:ss", Locale.US);
LocalTime time = LocalTime.now();
String f = formatter.format(time);
System.out.println(f);

(我更喜欢明确地使用美国的语言环境,以表明我不希望使用默认格式语言环境的任何内容。)


5

在你的第一行使用这个

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("HH:mm:ss");

2

-1

你可以通过在字符串上使用正则表达式来简单地完成它:

String f = formatter.format(time).replaceAll("\\.[^.]*", "");

这将删除(通过替换为空白)最后一个点和其后的所有内容。


3
我认为这更像是一个黑客行为。 - Shervin Asgari
@Shervin 为什么要称之为“hack”?这只是一个格式问题,有一个格式解决方案。从某种意义上说,它比编写自己的格式模式更优越,因为您不需要了解任何关于模式或如何编写模式的知识就可以使用它。 - Bohemian

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接