LocalDateTime remove the milliseconds
JavaDatabaseDateJava 8Java Problem Overview
I am working in java application where i am using the Java 8.
I have integrated the database(multiple database Oracle,Mysql,Postgres) and where in DB i string the created date.
the date format in DB is - 2015-07-29 16:23:28.143
I fetch this from DB and set in Localdatetime object
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
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
Can anybody know any solution on this.
Java Solutions
Solution 1 - Java
Truncate
You can drop anything less than seconds. Call LocalDateTime::truncatedTo
.
ldt = ldt.truncatedTo(ChronoUnit.SECONDS);
Solution 2 - Java
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.
Solution 3 - Java
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 WITHOUT DateFormatter (only using truncate
or withNano(0)
)
Observe the missing seconds here !