001package com.identityworksllc.iiq.common.query;
002
003import java.sql.PreparedStatement;
004import java.sql.ResultSet;
005import java.time.ZoneId;
006import java.time.ZonedDateTime;
007import java.util.Calendar;
008import java.util.Objects;
009import java.util.TimeZone;
010
011/**
012 * A small wrapper class for use with "Parameters" for setting a
013 * timestamp with timezone in a bulk context.
014 */
015public class TimestampWithTimezone extends java.sql.Timestamp {
016    /**
017     * The timezone associated with this timestamp
018     */
019    private final ZoneId timezone;
020
021    /**
022     * Creates a new instance from a Calendar, which must have a non-null time zone
023     * @param time The calendar instance
024     */
025    public TimestampWithTimezone(Calendar time) {
026        this(Objects.requireNonNull(time).getTimeInMillis(), Objects.requireNonNull(time.getTimeZone()).toZoneId());
027    }
028
029    /**
030     * Creates a new instance from a ZonedDateTime
031     * @param time The ZonedDateTime instance
032     */
033    public TimestampWithTimezone(ZonedDateTime time) {
034        this(Objects.requireNonNull(time).toInstant().toEpochMilli(), time.getZone());
035    }
036
037    /**
038     * Creates a new instance from an epoch millisecond timestamp and a TimeZone
039     * @param time The epoch millisecond timestamp
040     * @param tz The time zone
041     */
042    public TimestampWithTimezone(long time, TimeZone tz) {
043        this(time, Objects.requireNonNull(tz).toZoneId());
044    }
045
046    /**
047     * Creates a new instance from an epoch millisecond timestamp and a ZoneId
048     * @param time The epoch millisecond timestamp
049     * @param tz The zone ID
050     */
051    public TimestampWithTimezone(long time, ZoneId tz) {
052        super(time);
053        this.timezone = Objects.requireNonNull(tz);
054    }
055
056    /**
057     * Gets the ZoneId associated with this timestamp
058     * @return The zone ID
059     */
060    public ZoneId getZone() {
061        return timezone;
062    }
063
064    /**
065     * Gets the zoned calendar for use with PreparedStatement.setTimestamp and other methods
066     * @return The zoned calendar object
067     */
068    public Calendar getZonedCalendar() {
069        Calendar cal = Calendar.getInstance();
070        cal.setTimeInMillis(this.getTime());
071        cal.setTimeZone(TimeZone.getTimeZone(timezone));
072        return cal;
073    }
074}