The other Answers are correct but use troublesome old legacy date-time classes. Instead use java.time classes.
Conversion
New methods have been added to the old classes to facilitate conversion such as java.sql.Timestamp::toInstant()
.
java.sql.Timestamp ts = myResultSet.getTimestamp( … ) ;
Instant instant = ts.toInstant();
Instant
The Instant
class represents a moment on the timeline in UTC with a resolution of nanoseconds. Its toString
method generates a String in one of the standard ISO 8601 formats.
String output = instant.toString();
2011-12-03T10:15:30Z
You could replace the T
with a SPACE and delete the Z
to get your format.
output = output.replace( "T" , " ").replace( "Z" , "" ) ;
2011-12-03 10:15:30
ZonedDateTime
If you want to see the same moment but through the lens of a particular time zone, generate a ZonedDateTime
.
ZoneId zoneId = ZonedId.of( "America/Montreal" );
ZonedDateTime zdt = instant.atZone( zoneId );
Define a custom DateTimeFormatter
object. Or use DateTimeFormatter.ISO_LOCAL_DATE_TIME
and replace the T
with a SPACE.
String output = zdt.format( DateTimeFormatter.ISO_LOCAL_DATE_TIME ).replace( "T" , " " );
2011-12-03 05:15:30
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old date-time classes such as java.util.Date
, .Calendar
, & java.text.SimpleDateFormat
.
The Joda-Time project, now in maintenance mode, advises migration to java.time.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations.
Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport and further adapted to Android in ThreeTenABP (see How to use…).
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.