Skip to content

Instantly share code, notes, and snippets.

@dipu-bd
Last active January 26, 2021 12:03
Show Gist options
  • Save dipu-bd/2d240fb72046928af44d841f01badbaa to your computer and use it in GitHub Desktop.
Save dipu-bd/2d240fb72046928af44d841f01badbaa to your computer and use it in GitHub Desktop.
Test Timestamp and TimestampTZ data types of PostgreSQL
package com.test.time;
import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.PreparedStatementCallback;
import java.sql.Timestamp;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.util.Calendar;
import java.util.TimeZone;
public class TimestampTest {
private static final Logger log = LoggerFactory.getLogger(TimestampTest.class);
/*
SET timezone = 'Asia/Dhaka';
CREATE TABLE timestamp_demo (
ts TIMESTAMP,
tstz TIMESTAMPTZ
);
*/
public static void main(String[] args) throws Exception {
HikariConfig config = new HikariConfig();
config.setJdbcUrl("jdbc:postgresql://localhost:5432/****");
config.setUsername("***");
config.setPassword("***");
config.setDriverClassName("org.postgresql.Driver");
config.setMaximumPoolSize(40);
config.setMinimumIdle(2);
JdbcTemplate jt = new JdbcTemplate(new HikariDataSource(config));
// System variables
log.info("Timezone: {}", jt.queryForObject("SHOW TIMEZONE;", String.class));
log.info("Now: {}", jt.queryForObject("SELECT NOW();", String.class));
// Insert a new value
jt.execute("INSERT INTO timestamp_demo (ts, tstz) VALUES(?,?);", (PreparedStatementCallback<?>) ps -> {
ZonedDateTime saveMe = ZonedDateTime.now();
ps.setTimestamp(
1,
new Timestamp(saveMe.toInstant().toEpochMilli())
);
ps.setTimestamp(
2,
new Timestamp(saveMe.toInstant().toEpochMilli()),
Calendar.getInstance(TimeZone.getTimeZone(saveMe.getZone()))
);
return ps.execute();
});
// Query a value
jt.query("SELECT * FROM timestamp_demo", rs -> {
Timestamp ts = rs.getTimestamp("ts");
ZonedDateTime gotTs = ZonedDateTime.ofInstant(ts.toInstant(), ZoneId.of("UTC"));
log.info("Timestamp without zone: {}", gotTs);
Timestamp tstz = rs.getTimestamp("tstz");
ZonedDateTime gotTsTz = ZonedDateTime.ofInstant(tstz.toInstant(), ZoneId.of("UTC"));
log.info("Timestamp with zone: {}", gotTsTz);
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment