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