tl;dr
LocalDateTime.parse(
"2016-12-26 14:18:57.0".replace( " " , "T" )
)
.truncatedTo( ChronoUnit.SECONDS )
.toString()
.replace( "T" , " " )
Avoid legacy date-time classes
You are using troublesome old date-time classes, now legacy, supplanted by the java.time classes.
ISO 8601
First replace the SPACE in the middle of your input string to make it comply with the standard ISO 8601 format.
String input = "2016-12-26 14:18:57.0".replace( " " , "T" );
LocalDateTime
Parse as a LocalDateTime
given that your input string lacks any indication of offset-from-UTC or time zone.
LocalDateTime ldt = LocalDateTime.parse( input );
Generate a String by simply calling toString
. By default an ISO 8601 format is used to create the String. If the value has no fractional second, no decimal mark nor any fractional seconds digits appear.
String output = ldt.toString ();
ldt.toString(): 2016-12-26T14:18:57
If you dislike the T
in the middle, replace with a SPACE.
output = output.replace( "T" , " " );
2016-12-26 14:18:57
If your input might carry a fractional second and you want to delete that portion of data entirely rather than merely suppress its display, truncate the LocalDateTime
object.
LocalDateTime ldtTruncated = ldt.truncatedTo( ChronoUnit.SECONDS ); // Truncate any fraction of a second.
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.
Where to obtain the java.time classes?
- Java SE 8 and SE 9 and later
- Built-in.
- Part of the standard Java API with a bundled implementation.
- Java 9 adds some minor features and fixes.
- Java SE 6 and SE 7
- Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
- Android
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.