I should like to contribute the modern answer. When this question was asked in 2013, using the Timestamp
class was right, for example for storing a date-time into your database. Today the class is long outdated. The modern Java date and time API came out with Java 8 in the spring of 2014, three and a half years ago. I recommend you use this instead.
Depending on your situation an exact requirements, there are two natural replacements for Timestamp
:
Instant
is a point on the time-line. For most purposes I would consider it safest to use this. An Instant
is independent of time zone and will usually work well even in situations where your client device and your database server run different time zones.
LocalDateTime
is a date and time of day without time zone, like 2011-10-02 18:48:05.123 (to quote the question).
A modern JDBC driver (JDBC 4.2 or higher) and other modern tools for database access will be happy to store either an Instant
or a LocalDateTime
into your database column of datatype timestamp
. Both classes and the other date-time classes I am using in this answer belong to the modern API known as java.time
or JSR-310.
It’s easiest to convert your string to LocalDateTime
, so let’s take that first:
DateTimeFormatter formatter
= DateTimeFormatter.ofPattern("uuuu-MM-dd HH:mm:ss.SSS");
String text = "2011-10-02 18:48:05.123";
LocalDateTime dateTime = LocalDateTime.parse(text, formatter);
System.out.println(dateTime);
This prints
2011-10-02T18:48:05.123
If your string was in yyyy-MM-dd format, instead do:
String text = "2009-10-20";
LocalDateTime dateTime = LocalDate.parse(text).atStartOfDay();
System.out.println(dateTime);
This prints
2009-10-20T00:00
Or still better, take the output from LocalDate.parse()
and store it into a database column of datatype date
.
In both cases the procedure for converting from a LocalDateTime
to an Instant
is:
Instant ts = dateTime.atZone(ZoneId.systemDefault()).toInstant();
System.out.println(ts);
I have specified a conversion using the JVM’s default time zone because this is what the outdated class would have used. This is fragile, though, since the time zone setting may be changed under our feet by other parts of your program or by other programs running in the same JVM. If you can, specify a time zone in the region/city format instead, for example:
Instant ts = dateTime.atZone(ZoneId.of("Europe/Athens")).toInstant();