The Answer by assylias is correct. Here are some further thoughts.
Truncate
If you really do not want the fractional second at all, truncate to whole seconds.
Instant instant = Instant.now().truncatedTo( ChronoUnit.SECONDS ) ;
OffsetDateTime odt = OffsetDateTime.now().truncatedTo( ChronoUnit.SECONDS ) ;
ZonedDateTime zdt = ZonedDateTime.now().truncatedTo( ChronoUnit.SECONDS ) ;
The formatters used by the various toString
methods by default omit any text representing the fractional second if the value is zero.
So the value of:
2018-07-27T13:18:26.452+02:00
…becomes:
2018-07-27T13:18:26.000+02:00
…and its String
representation will be generated as seconds without a fraction:
2018-07-27T13:18:26+02:00
Try it.
OffsetDateTime odt = OffsetDateTime.parse( "2018-07-27T13:18:26.452+02:00" ) ;
OffsetDateTime odtTrunc = odt.truncatedTo( ChronoUnit.SECONDS ) ;
System.out.println( "odt.toString(): " + odt ) ;
System.out.println( "odtTrunc.toString(): " + odtTrunc ) ;
Try that code live at IdeOne.com.
odt.toString(): 2018-07-27T13:18:26.452+02:00
odtTrunc.toString(): 2018-07-27T13:18:26+02:00
Avoid legacy classes
The code in your Question confuses me. Do not mix the troublesome old legacy date-time classes such as Date
& SimpleDateFormat
with the modern java.time classes. The legacy classes are entirely supplanted by the modern ones.
Timeline
Be clear that LocalDateTime
serves a very different purpose than Instant
, OffsetDateTime
, and ZonedDateTime
. A LocalDateTime
object purposely lacks any concept of time zone or offset-from-UTC. So it cannot represent a moment, is not a point on the timeline.
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date
, Calendar
, & SimpleDateFormat
.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.*
classes.
Where to obtain the java.time classes?
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval
, YearWeek
, YearQuarter
, and more.