Java SQL Time toDate(TimeZone tz, int days)

Here you can find the source of toDate(TimeZone tz, int days)

Description

Returns the SQL Date object matching the given bytes with Oid#DATE .

License

Open Source License

Parameter

Parameter Description
tz The timezone used.
bytes The binary encoded date value.

Return

The parsed date object.

Declaration

public static Date toDate(TimeZone tz, int days) 

Method Source Code


//package com.java2s;
import java.sql.Date;
import java.util.TimeZone;

public class Main {
    public static final long DATE_POSITIVE_INFINITY = 9223372036825200000l;
    public static final long DATE_NEGATIVE_INFINITY = -9223372036832400000l;
    public static final long DATE_POSITIVE_SMALLER_INFINITY = 185543533774800000l;
    public static final long DATE_NEGATIVE_SMALLER_INFINITY = -185543533774800000l;

    /**/*from   w  w  w  .  j a  v a2 s  . c o m*/
     * Returns the SQL Date object matching the given bytes with
     * {@link Oid#DATE}.
     * 
     * @param tz The timezone used.
     * @param bytes The binary encoded date value.
     * @return The parsed date object.
     */
    public static Date toDate(TimeZone tz, int days) {
        long secs = toJavaSecs(days * 86400L);
        long millis = secs * 1000L;
        int offset = tz.getOffset(millis);
        if (millis <= DATE_NEGATIVE_SMALLER_INFINITY) {
            millis = DATE_NEGATIVE_INFINITY;
            offset = 0;
        } else if (millis >= DATE_POSITIVE_SMALLER_INFINITY) {
            millis = DATE_POSITIVE_INFINITY;
            offset = 0;
        }
        return new Date(millis - offset);
    }

    /**
     * Converts the given postgresql seconds to java seconds.
     * Reverse engineered by inserting varying dates to postgresql
     * and tuning the formula until the java dates matched.
     * See {@link #toPgSecs} for the reverse operation.
     * 
     * @param secs Postgresql seconds.
     * @return Java seconds.
     */
    private static long toJavaSecs(long secs) {
        // postgres epoc to java epoc
        secs += 946684800L;

        // Julian/Gregorian calendar cutoff point
        if (secs < -12219292800L) { // October 4, 1582 -> October 15, 1582
            secs += 86400 * 10;
            if (secs < -14825808000L) { // 1500-02-28 -> 1500-03-01
                int extraLeaps = (int) ((secs + 14825808000L) / 3155760000L);
                extraLeaps--;
                extraLeaps -= extraLeaps / 4;
                secs += extraLeaps * 86400L;
            }
        }
        return secs;
    }
}

Related

  1. sqlDateTimeAdd(java.util.Date date, long milliseconds)
  2. sqlTime()
  3. str2dateTime(String handedate)
  4. StrToDateTime(String val)
  5. strToTime(String strDate)
  6. toDateFromTime(String time)
  7. todayBeginTime()
  8. toGMTTime(long local)
  9. toMySQLDate(LocalDateTime dateTime)