I am providing the modern answer. The Timestamp
class was always poorly designed, a real hack on top of the already poorly designed Date
class. Both those classes are now long outdated. Don’t use them.
When the question was asked, you would need a Timestamp
for sending a point in time to the SQL database. Since JDBC 4.2 that is no longer the case. Assuming your database needs a timestamp with time zone
(recommended for true timestamps), pass it an OffsetDateTime
.
Before we can do that we need to overcome a real trouble with your sample string, Mon May 27 11:46:15 IST 2013
: the time zone abbreviation. IST
may mean Irish Summer Time, Israel Standard Time or India Standard Time (I have even read that Java may parse it into Atlantic/Reykjavik time zone — Icelandic Standard Time?) To control the interpretation we pass our preferred time zone to the formatter that we are using for parsing.
DateTimeFormatter formatter = new DateTimeFormatterBuilder()
.appendPattern("EEE MMM dd HH:mm:ss ")
.appendZoneText(TextStyle.SHORT, Set.of(ZoneId.of("Asia/Kolkata")))
.appendPattern(" yyyy")
.toFormatter(Locale.ROOT);
String dateString = "Mon May 27 11:46:15 IST 2013";
OffsetDateTime dateTime = formatter.parse(dateString, Instant::from)
.atOffset(ZoneOffset.UTC);
System.out.println(dateTime);
This snippet prints:
2013-05-27T06:16:15Z
This is the UTC equivalent of your string (assuming IST was for India Standard Time). Pass the OffsetDateTime
to your database using one of the PreparedStatement.setObject
methods (not setTimestamp
).
How can I convert this into timestamp and calculate in seconds the difference between the same and current time?
Calculating the difference in seconds goes very naturally with java.time:
long differenceInSeconds = ChronoUnit.SECONDS
.between(dateTime, OffsetDateTime.now(ZoneOffset.UTC));
System.out.println(differenceInSeconds);
When running just now I got:
202213260
Link: Oracle tutorial: Date Time explaining how to use java.time.