LocalDateTime 删除毫秒

我正在使用 Java8开发 Java 应用程序。

我已经集成了数据库(多个数据库 Oracle,Myql,Postgres)和在 DB i 字符串的创建日期。

DB 的日期格式是 -2015-07-2916:23:28.143

我从 DB 获取这个并设置为 Localdatetime 对象

myObj.setCreated(rs.getTimestamp("created").toLocalDateTime());

这里的问题是,我不想在响应中显示/发送毫秒。我想显示/发送日期像2015-07-2916:23:28

我试过格式化程序,但是它失败了,因为它给出了一个字符串,我不想把 LocalDateTime 对象更改为 String,因为这会导致所有 Java 应用程序的重大变化

有人知道怎么解决这个问题吗?

84828 次浏览

Simply set them to 0:

myObj.setCreated(rs.getTimestamp("created").toLocalDateTime().withNano(0));

Sample/proof:

import java.time.LocalDateTime;


public class DateTimeSample {


public static void main(String[] args) {
LocalDateTime ldt = LocalDateTime.now();
System.out.println(ldt);
System.out.println(ldt.withNano(0));
}
}

Output:

2015-07-30T16:29:11.684
2015-07-30T16:29:11

Author's note: Although this is the accepted one, Peter Lawrey's answer is IMHO preferrable because it makes the intention more clear.

Truncate

You can drop anything less than seconds. Call LocalDateTime::truncatedTo.

ldt = ldt.truncatedTo(ChronoUnit.SECONDS);

Providing code and logs to Happy Family comment at Marvin answer for those for whom STRING works,

!!! I as well fell into the same trap !!!

Issue:

withNano(0) and truncatedTo(ChronoUnit.SECONDS) will also remove seconds if the seconds are as :00 (At clock, seconds hand at 12 up straight)

Further Stretching Marvin's example output

2015-07-30T16:29:11.684
2015-07-30T16:29:11
2015-07-30T16:31 // for actual time 2015-07-30T16:31:00.684
2015-07-30T16:31 // for actual time 2015-07-30T16:31:00.888

Above behaviour which could cause BUG:

As you eliminate the nano seconds, if seconds turn up as :00, they skip from being printed

RESOLUTION:

public class WithNanoTest {
public static void main(String[] args) throws InterruptedException {
while (true) {
Thread.sleep(500);


DateTimeFormatter dtf = DateTimeFormatter.ISO_LOCAL_DATE_TIME;
System.out.println("truncate :::: " + LocalDateTime.now().truncatedTo(ChronoUnit.SECONDS).format(dtf));
System.out.println("withNano :::: " + LocalDateTime.now().withNano(0).format(dtf));
}
}
}

Screenshot of logs

Logs using DateFormatter

Logs using DateFormatter

Logs WITHOUT DateFormatter (only using truncate or withNano(0))

Observe the missing seconds here !

Logs WITHOUT DateFormatter

This is essentially a wired bug we faced very recently. So to conversion purpose I personally prefer to set up the format then convert accordingly with DateTimeFormatter

DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS").withZone(ZoneOffset.UTC);
myObject.setEventStartTimestamp(dateTimeFormatter.format(eventStartTime));

Here, if you don't need the milliseconds then take it off form the pattern. It will provide the exact format you are looking for. Also if you want to set your local time you can choose your timezone like ZoneOffset.EST or ZoneOffset.MT or ZoneOffset.PST