Reputation: 67
I'm trying to convert string timestamp having timezone in it to a timestamp with the same timezone. However, when executing the below code, I'm getting default system timestamp. Can someone help me on this. Below is the code I'm trying.
try {
Date dt = new Date();
SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
f.setTimeZone(TimeZone.getTimeZone("GMT"));
String dateString = f.format(dt);
System.out.println("DateString: "+dateString);
Date parsedDate = f.parse(dateString);
System.out.println("ParsedDate: "+parsedDate);
Timestamp timestamp = new Timestamp(parsedDate.getTime());
System.out.println("Timestamp: "+timestamp);
}catch (Exception e) {
// TODO: handle exception
}
When executing the above code, I get below result:
DateString: 2021-03-26T06:57:05.982+0000
ParsedDate: Fri Mar 26 12:27:05 IST 2021
Timestamp: 2021-03-26 12:27:05.982
But I have to get output in Timestamp as 2021-03-26T06:57:05.982+0000
Upvotes: 0
Views: 8672
Reputation: 86333
You don’t need any formatting, parsing nor conversion. To insert the current timestamp into your SQL database:
OffsetDateTime currentTimestamp = OffsetDateTime.now(ZoneOffset.UTC);
String sql = "insert into your_table(your_timestamp_with_time_zone_column) values (?);";
try (PreparedStatement prepStmt = yourDatabaseConnection.prepareStatement(sql)) {
prepStmt.setObject(1, currentTimestamp);
prepStmt.executeUpdate();
}
Upvotes: 0
Reputation: 18418
Your code using java.time classes:
ZonedDateTime zdt = ZonedDateTime.now();
DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
DateTimeFormatter dfGMT = df.withZone(ZoneId.of("GMT"));
String dateString = dfGMT.format(zdt);
System.out.println("DateString: "+dateString);
ZonedDateTime parsedDate = ZonedDateTime.parse(dateString,dfGMT);
System.out.println("ParsedDate: "+ parsedDate);
Timestamp timestamp = Timestamp.from(parsedDate.toInstant());
System.out.println("Zoned Timestamp: "+timestamp);
//ignoring zone info from date string
LocalDateTime ldt = LocalDateTime.from(dfGMT.parse(dateString));
timestamp = Timestamp.valueOf(ldt);
System.out.println("Zone stripped GMT timestamp: "+timestamp);
ZonedDateTime zdt1 = ldt.atZone(ZoneId.of("GMT"));
zdt1 = zdt1.withZoneSameInstant(ZoneId.of("America/Chicago"));
timestamp = Timestamp.valueOf(zdt1.toLocalDateTime());
System.out.println("Zone stripped CST timestamp: "+timestamp);
Output:
DateString: 2021-03-26T09:10:37.537+0000
ParsedDate: 2021-03-26T09:10:37.537Z[GMT]
Zoned Timestamp: 2021-03-26 14:40:37.537
Zone stripped GMT timestamp: 2021-03-26 09:10:37.537
Zone stripped CST timestamp: 2021-03-26 04:10:37.537
Upvotes: 2