编辑:我应该补充一点,这些是纳秒而不是毫秒。
我觉得这些答案并没有真正回答使用Java 8 SE日期和时间API的问题。我相信截断To方法是这里的解决方案。
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