TL; DR
LocalDateTime.parse( "2012-03-04 00:00:00.0".replace( " " , "T" ) ).format( DateTimeFormatter.ofPattern( "uuuu-MM-dd HH:mm:ss" ) )
java.time
Other answers use the nasty old time classes, which are now obsolete, completely superseded by modern java.time classes. For earlier Android, see Recent Bullets below.
Parse as a LocalDateTime
object, since your input does not contain any timezone or LocalDateTime
offset.
String input = "2012-03-04 00:00:00.0".replace( " " , "T" ) ; LocalDateTime ldt = LocalDateTime.parse( input ) ;
If you really don't care about fractional seconds, chop it off.
LocalDateTime ldtTruncated = ldt.truncatedTo( ChronoUnit.SECONDS ) ;
Specify your own format to use when creating a string to represent this value.
DateTimeFormatter f = DateTimeFormatter.ofPattern( "uuuu-MM-dd HH:mm:ss" ) ; String output = ldtTruncated.format( f ) ;
Dump for the console.
System.out.println( "input: " + input ) ; System.out.println( "ldt: " + ldt ) ; System.out.println( "ldtTruncated: " + ldtTruncated ) ; System.out.println( "output: " + output ) ;
See this code run on IdeOne.com .
input: 2012-03-04T00: 00: 00.0
ldt: 2012-03-04T00: 00
ldtTruncated: 2012-03-04T00: 00
: 2012-03-04 00:00:00
About java.time
The java.time framework is built into Java 8 and later. These classes supersede the nasty old legacy time classes such as java.util.Date
, Calendar
and SimpleDateFormat
.
The Joda-Time project, now in maintenance mode , we recommend switching to the java.time classes.
To learn more, see the Oracle Tutorial . And search for qaru for many examples and explanations. JSR 310 specification .
Where to get java.time classes?