Java LocalDateTime 删除毫秒
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/31726418/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
LocalDateTime remove the milliseconds
提问by Nitin Murlidhar Gaikwad
I am working in java application where i am using the Java 8.
我在使用 Java 8 的 Java 应用程序中工作。
I have integrated the database(multiple database Oracle,Mysql,Postgres) and where in DB i string the created date.
我已经集成了数据库(多个数据库 Oracle、Mysql、Postgres),并且在 DB 中我将创建日期字符串化。
the date format in DB is - 2015-07-29 16:23:28.143
DB 中的日期格式是 - 2015-07-29 16:23:28.143
I fetch this from DB and set in Localdatetime object
我从数据库中获取它并在 Localdatetime 对象中设置
myObj.setCreated(rs.getTimestamp("created").toLocalDateTime());
So here the issue is i dont want to show/send the millisecond in the response. i want to show/send date like 2015-07-29 16:23:28
所以这里的问题是我不想在响应中显示/发送毫秒。我想显示/发送日期,如 2015-07-29 16:23:28
I tried the formatter but it fails as it giving string and i dont want change the LocalDateTime object to String as this going to cause major change in all Java application.So want to find the solution
我尝试了格式化程序,但它失败了,因为它给出了字符串,我不想将 LocalDateTime 对象更改为 String,因为这会导致所有 Java 应用程序发生重大变化。所以想找到解决方案
Can anybody know any solution on this.
任何人都可以知道任何解决方案。
采纳答案by Marvin
Simply set them to 0
:
只需将它们设置为0
:
myObj.setCreated(rs.getTimestamp("created").toLocalDateTime().withNano(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
回答by Peter Lawrey
You could try this to drop anything less than seconds
你可以试试这个在几秒钟内放下任何东西
ldt = ldt.truncatedTo(ChronoUnit.SECONDS);