]> granicus.if.org Git - postgresql/blobdiff - src/backend/utils/adt/date.c
pgindent run for 8.3.
[postgresql] / src / backend / utils / adt / date.c
index 1caa68d774ba5a191a5394deeb077111ad7ec35e..0f2b44b356979c849b19cc47f83640035f4f552b 100644 (file)
@@ -3,12 +3,12 @@
  * date.c
  *       implements DATE and TIME data types specified in SQL-92 standard
  *
- * Portions Copyright (c) 1996-2003, PostgreSQL Global Development Group
+ * Portions Copyright (c) 1996-2007, PostgreSQL Global Development Group
  * Portions Copyright (c) 1994-5, Regents of the University of California
  *
  *
  * IDENTIFICATION
- *       $PostgreSQL: pgsql/src/backend/utils/adt/date.c,v 1.99 2004/06/03 02:08:04 tgl Exp $
+ *       $PostgreSQL: pgsql/src/backend/utils/adt/date.c,v 1.137 2007/11/15 21:14:38 momjian Exp $
  *
  *-------------------------------------------------------------------------
  */
 #include <ctype.h>
 #include <limits.h>
 #include <float.h>
+#include <time.h>
 
 #include "access/hash.h"
 #include "libpq/pqformat.h"
 #include "miscadmin.h"
 #include "parser/scansup.h"
+#include "utils/array.h"
 #include "utils/builtins.h"
 #include "utils/date.h"
 #include "utils/nabstime.h"
-#include "utils/timestamp.h"
 
 /*
  * gcc's -ffast-math switch breaks routines that expect exact results from
- * expressions like timeval / 3600, where timeval is double.
+ * expressions like timeval / SECS_PER_HOUR, where timeval is double.
  */
 #ifdef __FAST_MATH__
 #error -ffast-math is known to break this code
@@ -43,6 +44,61 @@ static int   tm2time(struct pg_tm * tm, fsec_t fsec, TimeADT *result);
 static int     tm2timetz(struct pg_tm * tm, fsec_t fsec, int tz, TimeTzADT *result);
 static void AdjustTimeForTypmod(TimeADT *time, int32 typmod);
 
+
+/* common code for timetypmodin and timetztypmodin */
+static int32
+anytime_typmodin(bool istz, ArrayType *ta)
+{
+       int32           typmod;
+       int32      *tl;
+       int                     n;
+
+       tl = ArrayGetIntegerTypmods(ta, &n);
+
+       /*
+        * we're not too tense about good error message here because grammar
+        * shouldn't allow wrong number of modifiers for TIME
+        */
+       if (n != 1)
+               ereport(ERROR,
+                               (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
+                                errmsg("invalid type modifier")));
+
+       if (*tl < 0)
+               ereport(ERROR,
+                               (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
+                                errmsg("TIME(%d)%s precision must not be negative",
+                                               *tl, (istz ? " WITH TIME ZONE" : ""))));
+       if (*tl > MAX_TIME_PRECISION)
+       {
+               ereport(WARNING,
+                               (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
+                                errmsg("TIME(%d)%s precision reduced to maximum allowed, %d",
+                                               *tl, (istz ? " WITH TIME ZONE" : ""),
+                                               MAX_TIME_PRECISION)));
+               typmod = MAX_TIME_PRECISION;
+       }
+       else
+               typmod = *tl;
+
+       return typmod;
+}
+
+/* common code for timetypmodout and timetztypmodout */
+static char *
+anytime_typmodout(bool istz, int32 typmod)
+{
+       char       *res = (char *) palloc(64);
+       const char *tz = istz ? " with time zone" : " without time zone";
+
+       if (typmod >= 0)
+               snprintf(res, 64, "(%d)%s", (int) typmod, tz);
+       else
+               snprintf(res, 64, "%s", tz);
+       return res;
+}
+
+
 /*****************************************************************************
  *      Date ADT
  *****************************************************************************/
@@ -57,7 +113,7 @@ date_in(PG_FUNCTION_ARGS)
        char       *str = PG_GETARG_CSTRING(0);
        DateADT         date;
        fsec_t          fsec;
-       struct pg_tm    tt,
+       struct pg_tm tt,
                           *tm = &tt;
        int                     tzp;
        int                     dtype;
@@ -65,12 +121,10 @@ date_in(PG_FUNCTION_ARGS)
        int                     dterr;
        char       *field[MAXDATEFIELDS];
        int                     ftype[MAXDATEFIELDS];
-       char            lowstr[MAXDATELEN + 1];
+       char            workbuf[MAXDATELEN + 1];
 
-       if (strlen(str) >= sizeof(lowstr))
-               dterr = DTERR_BAD_FORMAT;
-       else
-               dterr = ParseDateTime(str, lowstr, field, ftype, MAXDATEFIELDS, &nf);
+       dterr = ParseDateTime(str, workbuf, sizeof(workbuf),
+                                                 field, ftype, MAXDATEFIELDS, &nf);
        if (dterr == 0)
                dterr = DecodeDateTime(field, ftype, nf, &dtype, tm, &fsec, &tzp);
        if (dterr != 0)
@@ -84,7 +138,7 @@ date_in(PG_FUNCTION_ARGS)
                case DTK_CURRENT:
                        ereport(ERROR,
                                        (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
-                                        errmsg("date/time value \"current\" is no longer supported")));
+                         errmsg("date/time value \"current\" is no longer supported")));
 
                        GetCurrentDateTime(tm);
                        break;
@@ -98,6 +152,11 @@ date_in(PG_FUNCTION_ARGS)
                        break;
        }
 
+       if (!IS_VALID_JULIAN(tm->tm_year, tm->tm_mon, tm->tm_mday))
+               ereport(ERROR,
+                               (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
+                                errmsg("date out of range: \"%s\"", str)));
+
        date = date2j(tm->tm_year, tm->tm_mon, tm->tm_mday) - POSTGRES_EPOCH_JDATE;
 
        PG_RETURN_DATEADT(date);
@@ -111,7 +170,7 @@ date_out(PG_FUNCTION_ARGS)
 {
        DateADT         date = PG_GETARG_DATEADT(0);
        char       *result;
-       struct pg_tm    tt,
+       struct pg_tm tt,
                           *tm = &tt;
        char            buf[MAXDATELEN + 1];
 
@@ -278,21 +337,32 @@ date_mii(PG_FUNCTION_ARGS)
  * time zone
  */
 
+static Timestamp
+date2timestamp(DateADT dateVal)
+{
+       Timestamp       result;
+
 #ifdef HAVE_INT64_TIMESTAMP
-/* date is days since 2000, timestamp is microseconds since same... */
-#define date2timestamp(dateVal) \
-       ((Timestamp) ((dateVal) * INT64CONST(86400000000)))
+       /* date is days since 2000, timestamp is microseconds since same... */
+       result = dateVal * USECS_PER_DAY;
+       /* Date's range is wider than timestamp's, so must check for overflow */
+       if (result / USECS_PER_DAY != dateVal)
+               ereport(ERROR,
+                               (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
+                                errmsg("date out of range for timestamp")));
 #else
-/* date is days since 2000, timestamp is seconds since same... */
-#define date2timestamp(dateVal) \
-       ((Timestamp) ((dateVal) * 86400.0))
+       /* date is days since 2000, timestamp is seconds since same... */
+       result = dateVal * (double) SECS_PER_DAY;
 #endif
 
+       return result;
+}
+
 static TimestampTz
 date2timestamptz(DateADT dateVal)
 {
        TimestampTz result;
-       struct pg_tm    tt,
+       struct pg_tm tt,
                           *tm = &tt;
        int                     tz;
 
@@ -302,13 +372,17 @@ date2timestamptz(DateADT dateVal)
        tm->tm_hour = 0;
        tm->tm_min = 0;
        tm->tm_sec = 0;
-       tz = DetermineLocalTimeZone(tm);
+       tz = DetermineTimeZoneOffset(tm, session_timezone);
 
 #ifdef HAVE_INT64_TIMESTAMP
-       result = (dateVal * INT64CONST(86400000000))
-               + (tz * INT64CONST(1000000));
+       result = dateVal * USECS_PER_DAY + tz * USECS_PER_SEC;
+       /* Date's range is wider than timestamp's, so must check for overflow */
+       if ((result - tz * USECS_PER_SEC) / USECS_PER_DAY != dateVal)
+               ereport(ERROR,
+                               (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
+                                errmsg("date out of range for timestamp")));
 #else
-       result = dateVal * 86400.0 + tz;
+       result = dateVal * (double) SECS_PER_DAY + tz;
 #endif
 
        return result;
@@ -407,8 +481,8 @@ Datum
 date_eq_timestamptz(PG_FUNCTION_ARGS)
 {
        DateADT         dateVal = PG_GETARG_DATEADT(0);
-       TimestampTz     dt2 = PG_GETARG_TIMESTAMPTZ(1);
-       TimestampTz     dt1;
+       TimestampTz dt2 = PG_GETARG_TIMESTAMPTZ(1);
+       TimestampTz dt1;
 
        dt1 = date2timestamptz(dateVal);
 
@@ -419,8 +493,8 @@ Datum
 date_ne_timestamptz(PG_FUNCTION_ARGS)
 {
        DateADT         dateVal = PG_GETARG_DATEADT(0);
-       TimestampTz     dt2 = PG_GETARG_TIMESTAMPTZ(1);
-       TimestampTz     dt1;
+       TimestampTz dt2 = PG_GETARG_TIMESTAMPTZ(1);
+       TimestampTz dt1;
 
        dt1 = date2timestamptz(dateVal);
 
@@ -431,8 +505,8 @@ Datum
 date_lt_timestamptz(PG_FUNCTION_ARGS)
 {
        DateADT         dateVal = PG_GETARG_DATEADT(0);
-       TimestampTz     dt2 = PG_GETARG_TIMESTAMPTZ(1);
-       TimestampTz     dt1;
+       TimestampTz dt2 = PG_GETARG_TIMESTAMPTZ(1);
+       TimestampTz dt1;
 
        dt1 = date2timestamptz(dateVal);
 
@@ -443,8 +517,8 @@ Datum
 date_gt_timestamptz(PG_FUNCTION_ARGS)
 {
        DateADT         dateVal = PG_GETARG_DATEADT(0);
-       TimestampTz     dt2 = PG_GETARG_TIMESTAMPTZ(1);
-       TimestampTz     dt1;
+       TimestampTz dt2 = PG_GETARG_TIMESTAMPTZ(1);
+       TimestampTz dt1;
 
        dt1 = date2timestamptz(dateVal);
 
@@ -455,8 +529,8 @@ Datum
 date_le_timestamptz(PG_FUNCTION_ARGS)
 {
        DateADT         dateVal = PG_GETARG_DATEADT(0);
-       TimestampTz     dt2 = PG_GETARG_TIMESTAMPTZ(1);
-       TimestampTz     dt1;
+       TimestampTz dt2 = PG_GETARG_TIMESTAMPTZ(1);
+       TimestampTz dt1;
 
        dt1 = date2timestamptz(dateVal);
 
@@ -467,8 +541,8 @@ Datum
 date_ge_timestamptz(PG_FUNCTION_ARGS)
 {
        DateADT         dateVal = PG_GETARG_DATEADT(0);
-       TimestampTz     dt2 = PG_GETARG_TIMESTAMPTZ(1);
-       TimestampTz     dt1;
+       TimestampTz dt2 = PG_GETARG_TIMESTAMPTZ(1);
+       TimestampTz dt1;
 
        dt1 = date2timestamptz(dateVal);
 
@@ -479,8 +553,8 @@ Datum
 date_cmp_timestamptz(PG_FUNCTION_ARGS)
 {
        DateADT         dateVal = PG_GETARG_DATEADT(0);
-       TimestampTz     dt2 = PG_GETARG_TIMESTAMPTZ(1);
-       TimestampTz     dt1;
+       TimestampTz dt2 = PG_GETARG_TIMESTAMPTZ(1);
+       TimestampTz dt1;
 
        dt1 = date2timestamptz(dateVal);
 
@@ -574,9 +648,9 @@ timestamp_cmp_date(PG_FUNCTION_ARGS)
 Datum
 timestamptz_eq_date(PG_FUNCTION_ARGS)
 {
-       TimestampTz     dt1 = PG_GETARG_TIMESTAMPTZ(0);
+       TimestampTz dt1 = PG_GETARG_TIMESTAMPTZ(0);
        DateADT         dateVal = PG_GETARG_DATEADT(1);
-       TimestampTz     dt2;
+       TimestampTz dt2;
 
        dt2 = date2timestamptz(dateVal);
 
@@ -586,9 +660,9 @@ timestamptz_eq_date(PG_FUNCTION_ARGS)
 Datum
 timestamptz_ne_date(PG_FUNCTION_ARGS)
 {
-       TimestampTz     dt1 = PG_GETARG_TIMESTAMPTZ(0);
+       TimestampTz dt1 = PG_GETARG_TIMESTAMPTZ(0);
        DateADT         dateVal = PG_GETARG_DATEADT(1);
-       TimestampTz     dt2;
+       TimestampTz dt2;
 
        dt2 = date2timestamptz(dateVal);
 
@@ -598,9 +672,9 @@ timestamptz_ne_date(PG_FUNCTION_ARGS)
 Datum
 timestamptz_lt_date(PG_FUNCTION_ARGS)
 {
-       TimestampTz     dt1 = PG_GETARG_TIMESTAMPTZ(0);
+       TimestampTz dt1 = PG_GETARG_TIMESTAMPTZ(0);
        DateADT         dateVal = PG_GETARG_DATEADT(1);
-       TimestampTz     dt2;
+       TimestampTz dt2;
 
        dt2 = date2timestamptz(dateVal);
 
@@ -610,9 +684,9 @@ timestamptz_lt_date(PG_FUNCTION_ARGS)
 Datum
 timestamptz_gt_date(PG_FUNCTION_ARGS)
 {
-       TimestampTz     dt1 = PG_GETARG_TIMESTAMPTZ(0);
+       TimestampTz dt1 = PG_GETARG_TIMESTAMPTZ(0);
        DateADT         dateVal = PG_GETARG_DATEADT(1);
-       TimestampTz     dt2;
+       TimestampTz dt2;
 
        dt2 = date2timestamptz(dateVal);
 
@@ -622,9 +696,9 @@ timestamptz_gt_date(PG_FUNCTION_ARGS)
 Datum
 timestamptz_le_date(PG_FUNCTION_ARGS)
 {
-       TimestampTz     dt1 = PG_GETARG_TIMESTAMPTZ(0);
+       TimestampTz dt1 = PG_GETARG_TIMESTAMPTZ(0);
        DateADT         dateVal = PG_GETARG_DATEADT(1);
-       TimestampTz     dt2;
+       TimestampTz dt2;
 
        dt2 = date2timestamptz(dateVal);
 
@@ -634,9 +708,9 @@ timestamptz_le_date(PG_FUNCTION_ARGS)
 Datum
 timestamptz_ge_date(PG_FUNCTION_ARGS)
 {
-       TimestampTz     dt1 = PG_GETARG_TIMESTAMPTZ(0);
+       TimestampTz dt1 = PG_GETARG_TIMESTAMPTZ(0);
        DateADT         dateVal = PG_GETARG_DATEADT(1);
-       TimestampTz     dt2;
+       TimestampTz dt2;
 
        dt2 = date2timestamptz(dateVal);
 
@@ -646,9 +720,9 @@ timestamptz_ge_date(PG_FUNCTION_ARGS)
 Datum
 timestamptz_cmp_date(PG_FUNCTION_ARGS)
 {
-       TimestampTz     dt1 = PG_GETARG_TIMESTAMPTZ(0);
+       TimestampTz dt1 = PG_GETARG_TIMESTAMPTZ(0);
        DateADT         dateVal = PG_GETARG_DATEADT(1);
-       TimestampTz     dt2;
+       TimestampTz dt2;
 
        dt2 = date2timestamptz(dateVal);
 
@@ -719,14 +793,14 @@ timestamp_date(PG_FUNCTION_ARGS)
 {
        Timestamp       timestamp = PG_GETARG_TIMESTAMP(0);
        DateADT         result;
-       struct pg_tm    tt,
+       struct pg_tm tt,
                           *tm = &tt;
        fsec_t          fsec;
 
        if (TIMESTAMP_NOT_FINITE(timestamp))
                PG_RETURN_NULL();
 
-       if (timestamp2tm(timestamp, NULL, tm, &fsec, NULL) != 0)
+       if (timestamp2tm(timestamp, NULL, tm, &fsec, NULL, NULL) != 0)
                ereport(ERROR,
                                (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
                                 errmsg("timestamp out of range")));
@@ -760,7 +834,7 @@ timestamptz_date(PG_FUNCTION_ARGS)
 {
        TimestampTz timestamp = PG_GETARG_TIMESTAMP(0);
        DateADT         result;
-       struct pg_tm    tt,
+       struct pg_tm tt,
                           *tm = &tt;
        fsec_t          fsec;
        int                     tz;
@@ -769,7 +843,7 @@ timestamptz_date(PG_FUNCTION_ARGS)
        if (TIMESTAMP_NOT_FINITE(timestamp))
                PG_RETURN_NULL();
 
-       if (timestamp2tm(timestamp, &tz, tm, &fsec, &tzn) != 0)
+       if (timestamp2tm(timestamp, &tz, tm, &fsec, &tzn, NULL) != 0)
                ereport(ERROR,
                                (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
                                 errmsg("timestamp out of range")));
@@ -788,7 +862,7 @@ abstime_date(PG_FUNCTION_ARGS)
 {
        AbsoluteTime abstime = PG_GETARG_ABSOLUTETIME(0);
        DateADT         result;
-       struct pg_tm    tt,
+       struct pg_tm tt,
                           *tm = &tt;
        int                     tz;
 
@@ -799,11 +873,11 @@ abstime_date(PG_FUNCTION_ARGS)
                case NOEND_ABSTIME:
                        ereport(ERROR,
                                        (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
-                          errmsg("cannot convert reserved abstime value to date")));
+                                  errmsg("cannot convert reserved abstime value to date")));
 
                        /*
-                        * pretend to drop through to make compiler think that result
-                        * will be set
+                        * pretend to drop through to make compiler think that result will
+                        * be set
                         */
 
                default:
@@ -816,64 +890,6 @@ abstime_date(PG_FUNCTION_ARGS)
 }
 
 
-/* date_text()
- * Convert date to text data type.
- */
-Datum
-date_text(PG_FUNCTION_ARGS)
-{
-       /* Input is a Date, but may as well leave it in Datum form */
-       Datum           date = PG_GETARG_DATUM(0);
-       text       *result;
-       char       *str;
-       int                     len;
-
-       str = DatumGetCString(DirectFunctionCall1(date_out, date));
-
-       len = (strlen(str) + VARHDRSZ);
-
-       result = palloc(len);
-
-       VARATT_SIZEP(result) = len;
-       memmove(VARDATA(result), str, (len - VARHDRSZ));
-
-       pfree(str);
-
-       PG_RETURN_TEXT_P(result);
-}
-
-
-/* text_date()
- * Convert text string to date.
- * Text type is not null terminated, so use temporary string
- *     then call the standard input routine.
- */
-Datum
-text_date(PG_FUNCTION_ARGS)
-{
-       text       *str = PG_GETARG_TEXT_P(0);
-       int                     i;
-       char       *sp,
-                          *dp,
-                               dstr[MAXDATELEN + 1];
-
-       if (VARSIZE(str) - VARHDRSZ > MAXDATELEN)
-               ereport(ERROR,
-                               (errcode(ERRCODE_INVALID_DATETIME_FORMAT),
-                                errmsg("invalid input syntax for type date: \"%s\"",
-                                               VARDATA(str))));
-
-       sp = VARDATA(str);
-       dp = dstr;
-       for (i = 0; i < (VARSIZE(str) - VARHDRSZ); i++)
-               *dp++ = *sp++;
-       *dp = '\0';
-
-       return DirectFunctionCall1(date_in,
-                                                          CStringGetDatum(dstr));
-}
-
-
 /*****************************************************************************
  *      Time ADT
  *****************************************************************************/
@@ -889,20 +905,18 @@ time_in(PG_FUNCTION_ARGS)
        int32           typmod = PG_GETARG_INT32(2);
        TimeADT         result;
        fsec_t          fsec;
-       struct pg_tm    tt,
+       struct pg_tm tt,
                           *tm = &tt;
        int                     tz;
        int                     nf;
        int                     dterr;
-       char            lowstr[MAXDATELEN + 1];
+       char            workbuf[MAXDATELEN + 1];
        char       *field[MAXDATEFIELDS];
        int                     dtype;
        int                     ftype[MAXDATEFIELDS];
 
-       if (strlen(str) >= sizeof(lowstr))
-               dterr = DTERR_BAD_FORMAT;
-       else
-               dterr = ParseDateTime(str, lowstr, field, ftype, MAXDATEFIELDS, &nf);
+       dterr = ParseDateTime(str, workbuf, sizeof(workbuf),
+                                                 field, ftype, MAXDATEFIELDS, &nf);
        if (dterr == 0)
                dterr = DecodeTimeOnly(field, ftype, nf, &dtype, tm, &fsec, &tz);
        if (dterr != 0)
@@ -921,10 +935,10 @@ static int
 tm2time(struct pg_tm * tm, fsec_t fsec, TimeADT *result)
 {
 #ifdef HAVE_INT64_TIMESTAMP
-       *result = ((((((tm->tm_hour * 60) + tm->tm_min) * 60) + tm->tm_sec)
-                               * INT64CONST(1000000)) + fsec);
+       *result = ((((tm->tm_hour * MINS_PER_HOUR + tm->tm_min) * SECS_PER_MINUTE) + tm->tm_sec)
+                          * USECS_PER_SEC) + fsec;
 #else
-       *result = ((((tm->tm_hour * 60) + tm->tm_min) * 60) + tm->tm_sec + fsec);
+       *result = ((tm->tm_hour * MINS_PER_HOUR + tm->tm_min) * SECS_PER_MINUTE) + tm->tm_sec + fsec;
 #endif
        return 0;
 }
@@ -938,20 +952,28 @@ static int
 time2tm(TimeADT time, struct pg_tm * tm, fsec_t *fsec)
 {
 #ifdef HAVE_INT64_TIMESTAMP
-       tm->tm_hour = (time / INT64CONST(3600000000));
-       time -= (tm->tm_hour * INT64CONST(3600000000));
-       tm->tm_min = (time / INT64CONST(60000000));
-       time -= (tm->tm_min * INT64CONST(60000000));
-       tm->tm_sec = (time / INT64CONST(1000000));
-       time -= (tm->tm_sec * INT64CONST(1000000));
+       tm->tm_hour = time / USECS_PER_HOUR;
+       time -= tm->tm_hour * USECS_PER_HOUR;
+       tm->tm_min = time / USECS_PER_MINUTE;
+       time -= tm->tm_min * USECS_PER_MINUTE;
+       tm->tm_sec = time / USECS_PER_SEC;
+       time -= tm->tm_sec * USECS_PER_SEC;
        *fsec = time;
 #else
        double          trem;
 
+recalc:
        trem = time;
-       TMODULO(trem, tm->tm_hour, 3600e0);
-       TMODULO(trem, tm->tm_min, 60e0);
-       TMODULO(trem, tm->tm_sec, 1e0);
+       TMODULO(trem, tm->tm_hour, (double) SECS_PER_HOUR);
+       TMODULO(trem, tm->tm_min, (double) SECS_PER_MINUTE);
+       TMODULO(trem, tm->tm_sec, 1.0);
+       trem = TIMEROUND(trem);
+       /* roundoff may need to propagate to higher-order fields */
+       if (trem >= 1.0)
+       {
+               time = ceil(time);
+               goto recalc;
+       }
        *fsec = trem;
 #endif
 
@@ -963,7 +985,7 @@ time_out(PG_FUNCTION_ARGS)
 {
        TimeADT         time = PG_GETARG_TIMEADT(0);
        char       *result;
-       struct pg_tm    tt,
+       struct pg_tm tt,
                           *tm = &tt;
        fsec_t          fsec;
        char            buf[MAXDATELEN + 1];
@@ -986,11 +1008,21 @@ time_recv(PG_FUNCTION_ARGS)
 {
        StringInfo      buf = (StringInfo) PG_GETARG_POINTER(0);
 
+#ifdef NOT_USED
+       Oid                     typelem = PG_GETARG_OID(1);
+#endif
+       int32           typmod = PG_GETARG_INT32(2);
+       TimeADT         result;
+
 #ifdef HAVE_INT64_TIMESTAMP
-       PG_RETURN_TIMEADT((TimeADT) pq_getmsgint64(buf));
+       result = pq_getmsgint64(buf);
 #else
-       PG_RETURN_TIMEADT((TimeADT) pq_getmsgfloat8(buf));
+       result = pq_getmsgfloat8(buf);
 #endif
+
+       AdjustTimeForTypmod(&result, typmod);
+
+       PG_RETURN_TIMEADT(result);
 }
 
 /*
@@ -1011,6 +1043,22 @@ time_send(PG_FUNCTION_ARGS)
        PG_RETURN_BYTEA_P(pq_endtypsend(&buf));
 }
 
+Datum
+timetypmodin(PG_FUNCTION_ARGS)
+{
+       ArrayType  *ta = PG_GETARG_ARRAYTYPE_P(0);
+
+       PG_RETURN_INT32(anytime_typmodin(false, ta));
+}
+
+Datum
+timetypmodout(PG_FUNCTION_ARGS)
+{
+       int32           typmod = PG_GETARG_INT32(0);
+
+       PG_RETURN_CSTRING(anytime_typmodout(false, typmod));
+}
+
 
 /* time_scale()
  * Adjust time type for specified scale factor.
@@ -1059,7 +1107,6 @@ AdjustTimeForTypmod(TimeADT *time, int32 typmod)
                INT64CONST(5),
                INT64CONST(0)
        };
-
 #else
        /* note MAX_TIME_PRECISION differs in this case */
        static const double TimeScales[MAX_TIME_PRECISION + 1] = {
@@ -1077,29 +1124,24 @@ AdjustTimeForTypmod(TimeADT *time, int32 typmod)
        };
 #endif
 
-       if ((typmod >= 0) && (typmod <= MAX_TIME_PRECISION))
+       if (typmod >= 0 && typmod <= MAX_TIME_PRECISION)
        {
                /*
-                * Note: this round-to-nearest code is not completely consistent
-                * about rounding values that are exactly halfway between integral
-                * values.      On most platforms, rint() will implement
-                * round-to-nearest-even, but the integer code always rounds up
-                * (away from zero).  Is it worth trying to be consistent?
+                * Note: this round-to-nearest code is not completely consistent about
+                * rounding values that are exactly halfway between integral values.
+                * On most platforms, rint() will implement round-to-nearest-even, but
+                * the integer code always rounds up (away from zero).  Is it worth
+                * trying to be consistent?
                 */
 #ifdef HAVE_INT64_TIMESTAMP
                if (*time >= INT64CONST(0))
-               {
-                       *time = (((*time + TimeOffsets[typmod]) / TimeScales[typmod])
-                                        * TimeScales[typmod]);
-               }
+                       *time = ((*time + TimeOffsets[typmod]) / TimeScales[typmod]) *
+                               TimeScales[typmod];
                else
-               {
-                       *time = -((((-*time) + TimeOffsets[typmod]) / TimeScales[typmod])
-                                         * TimeScales[typmod]);
-               }
+                       *time = -((((-*time) + TimeOffsets[typmod]) / TimeScales[typmod]) *
+                                         TimeScales[typmod]);
 #else
-               *time = (rint(((double) *time) * TimeScales[typmod])
-                                / TimeScales[typmod]);
+               *time = rint((double) *time * TimeScales[typmod]) / TimeScales[typmod];
 #endif
        }
 }
@@ -1172,6 +1214,17 @@ time_cmp(PG_FUNCTION_ARGS)
        PG_RETURN_INT32(0);
 }
 
+Datum
+time_hash(PG_FUNCTION_ARGS)
+{
+       /* We can use either hashint8 or hashfloat8 directly */
+#ifdef HAVE_INT64_TIMESTAMP
+       return hashint8(fcinfo);
+#else
+       return hashfloat8(fcinfo);
+#endif
+}
+
 Datum
 time_larger(PG_FUNCTION_ARGS)
 {
@@ -1200,8 +1253,8 @@ Datum
 overlaps_time(PG_FUNCTION_ARGS)
 {
        /*
-        * The arguments are TimeADT, but we leave them as generic Datums to
-        * avoid dereferencing nulls (TimeADT is pass-by-reference!)
+        * The arguments are TimeADT, but we leave them as generic Datums to avoid
+        * dereferencing nulls (TimeADT is pass-by-reference!)
         */
        Datum           ts1 = PG_GETARG_DATUM(0);
        Datum           te1 = PG_GETARG_DATUM(1);
@@ -1218,9 +1271,9 @@ overlaps_time(PG_FUNCTION_ARGS)
        (DatumGetTimeADT(t1) < DatumGetTimeADT(t2))
 
        /*
-        * If both endpoints of interval 1 are null, the result is null
-        * (unknown). If just one endpoint is null, take ts1 as the non-null
-        * one. Otherwise, take ts1 as the lesser endpoint.
+        * If both endpoints of interval 1 are null, the result is null (unknown).
+        * If just one endpoint is null, take ts1 as the non-null one. Otherwise,
+        * take ts1 as the lesser endpoint.
         */
        if (ts1IsNull)
        {
@@ -1268,8 +1321,8 @@ overlaps_time(PG_FUNCTION_ARGS)
        if (TIMEADT_GT(ts1, ts2))
        {
                /*
-                * This case is ts1 < te2 OR te1 < te2, which may look redundant
-                * but in the presence of nulls it's not quite completely so.
+                * This case is ts1 < te2 OR te1 < te2, which may look redundant but
+                * in the presence of nulls it's not quite completely so.
                 */
                if (te2IsNull)
                        PG_RETURN_NULL();
@@ -1279,8 +1332,8 @@ overlaps_time(PG_FUNCTION_ARGS)
                        PG_RETURN_NULL();
 
                /*
-                * If te1 is not null then we had ts1 <= te1 above, and we just
-                * found ts1 >= te2, hence te1 >= te2.
+                * If te1 is not null then we had ts1 <= te1 above, and we just found
+                * ts1 >= te2, hence te1 >= te2.
                 */
                PG_RETURN_BOOL(false);
        }
@@ -1295,8 +1348,8 @@ overlaps_time(PG_FUNCTION_ARGS)
                        PG_RETURN_NULL();
 
                /*
-                * If te2 is not null then we had ts2 <= te2 above, and we just
-                * found ts2 >= te1, hence te2 >= te1.
+                * If te2 is not null then we had ts2 <= te2 above, and we just found
+                * ts2 >= te1, hence te2 >= te1.
                 */
                PG_RETURN_BOOL(false);
        }
@@ -1304,8 +1357,7 @@ overlaps_time(PG_FUNCTION_ARGS)
        {
                /*
                 * For ts1 = ts2 the spec says te1 <> te2 OR te1 = te2, which is a
-                * rather silly way of saying "true if both are nonnull, else
-                * null".
+                * rather silly way of saying "true if both are nonnull, else null".
                 */
                if (te1IsNull || te2IsNull)
                        PG_RETURN_NULL();
@@ -1324,14 +1376,14 @@ timestamp_time(PG_FUNCTION_ARGS)
 {
        Timestamp       timestamp = PG_GETARG_TIMESTAMP(0);
        TimeADT         result;
-       struct pg_tm    tt,
+       struct pg_tm tt,
                           *tm = &tt;
        fsec_t          fsec;
 
        if (TIMESTAMP_NOT_FINITE(timestamp))
                PG_RETURN_NULL();
 
-       if (timestamp2tm(timestamp, NULL, tm, &fsec, NULL) != 0)
+       if (timestamp2tm(timestamp, NULL, tm, &fsec, NULL, NULL) != 0)
                ereport(ERROR,
                                (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
                                 errmsg("timestamp out of range")));
@@ -1339,13 +1391,13 @@ timestamp_time(PG_FUNCTION_ARGS)
 #ifdef HAVE_INT64_TIMESTAMP
 
        /*
-        * Could also do this with time = (timestamp / 86400000000 *
-        * 86400000000) - timestamp;
+        * Could also do this with time = (timestamp / USECS_PER_DAY *
+        * USECS_PER_DAY) - timestamp;
         */
-       result = ((((((tm->tm_hour * 60) + tm->tm_min) * 60) + tm->tm_sec)
-                          * INT64CONST(1000000)) + fsec);
+       result = ((((tm->tm_hour * MINS_PER_HOUR + tm->tm_min) * SECS_PER_MINUTE) + tm->tm_sec) *
+                         USECS_PER_SEC) + fsec;
 #else
-       result = ((((tm->tm_hour * 60) + tm->tm_min) * 60) + tm->tm_sec + fsec);
+       result = ((tm->tm_hour * MINS_PER_HOUR + tm->tm_min) * SECS_PER_MINUTE) + tm->tm_sec + fsec;
 #endif
 
        PG_RETURN_TIMEADT(result);
@@ -1359,7 +1411,7 @@ timestamptz_time(PG_FUNCTION_ARGS)
 {
        TimestampTz timestamp = PG_GETARG_TIMESTAMP(0);
        TimeADT         result;
-       struct pg_tm    tt,
+       struct pg_tm tt,
                           *tm = &tt;
        int                     tz;
        fsec_t          fsec;
@@ -1368,7 +1420,7 @@ timestamptz_time(PG_FUNCTION_ARGS)
        if (TIMESTAMP_NOT_FINITE(timestamp))
                PG_RETURN_NULL();
 
-       if (timestamp2tm(timestamp, &tz, tm, &fsec, &tzn) != 0)
+       if (timestamp2tm(timestamp, &tz, tm, &fsec, &tzn, NULL) != 0)
                ereport(ERROR,
                                (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
                                 errmsg("timestamp out of range")));
@@ -1376,13 +1428,13 @@ timestamptz_time(PG_FUNCTION_ARGS)
 #ifdef HAVE_INT64_TIMESTAMP
 
        /*
-        * Could also do this with time = (timestamp / 86400000000 *
-        * 86400000000) - timestamp;
+        * Could also do this with time = (timestamp / USECS_PER_DAY *
+        * USECS_PER_DAY) - timestamp;
         */
-       result = ((((((tm->tm_hour * 60) + tm->tm_min) * 60) + tm->tm_sec)
-                          * INT64CONST(1000000)) + fsec);
+       result = ((((tm->tm_hour * MINS_PER_HOUR + tm->tm_min) * SECS_PER_MINUTE) + tm->tm_sec) *
+                         USECS_PER_SEC) + fsec;
 #else
-       result = ((((tm->tm_hour * 60) + tm->tm_min) * 60) + tm->tm_sec + fsec);
+       result = ((tm->tm_hour * MINS_PER_HOUR + tm->tm_min) * SECS_PER_MINUTE) + tm->tm_sec + fsec;
 #endif
 
        PG_RETURN_TIMEADT(result);
@@ -1399,7 +1451,7 @@ datetime_timestamp(PG_FUNCTION_ARGS)
        Timestamp       result;
 
        result = DatumGetTimestamp(DirectFunctionCall1(date_timestamp,
-                                                                                                DateADTGetDatum(date)));
+                                                                                                  DateADTGetDatum(date)));
        result += time;
 
        PG_RETURN_TIMESTAMP(result);
@@ -1417,6 +1469,7 @@ time_interval(PG_FUNCTION_ARGS)
        result = (Interval *) palloc(sizeof(Interval));
 
        result->time = time;
+       result->day = 0;
        result->month = 0;
 
        PG_RETURN_INTERVAL_P(result);
@@ -1440,20 +1493,20 @@ interval_time(PG_FUNCTION_ARGS)
        int64           days;
 
        result = span->time;
-       if (result >= INT64CONST(86400000000))
+       if (result >= USECS_PER_DAY)
        {
-               days = result / INT64CONST(86400000000);
-               result -= days * INT64CONST(86400000000);
+               days = result / USECS_PER_DAY;
+               result -= days * USECS_PER_DAY;
        }
        else if (result < 0)
        {
-               days = (-result + INT64CONST(86400000000) - 1) / INT64CONST(86400000000);
-               result += days * INT64CONST(86400000000);
+               days = (-result + USECS_PER_DAY - 1) / USECS_PER_DAY;
+               result += days * USECS_PER_DAY;
        }
 #else
        result = span->time;
-       if (result >= 86400e0 || result < 0)
-               result -= floor(result / 86400e0) * 86400e0;
+       if (result >= (double) SECS_PER_DAY || result < 0)
+               result -= floor(result / (double) SECS_PER_DAY) * (double) SECS_PER_DAY;
 #endif
 
        PG_RETURN_TIMEADT(result);
@@ -1471,8 +1524,9 @@ time_mi_time(PG_FUNCTION_ARGS)
 
        result = (Interval *) palloc(sizeof(Interval));
 
-       result->time = (time1 - time2);
        result->month = 0;
+       result->day = 0;
+       result->time = time1 - time2;
 
        PG_RETURN_INTERVAL_P(result);
 }
@@ -1488,17 +1542,17 @@ time_pl_interval(PG_FUNCTION_ARGS)
        TimeADT         result;
 
 #ifdef HAVE_INT64_TIMESTAMP
-       result = (time + span->time);
-       result -= (result / INT64CONST(86400000000) * INT64CONST(86400000000));
+       result = time + span->time;
+       result -= result / USECS_PER_DAY * USECS_PER_DAY;
        if (result < INT64CONST(0))
-               result += INT64CONST(86400000000);
+               result += USECS_PER_DAY;
 #else
        TimeADT         time1;
 
-       result = (time + span->time);
-       TMODULO(result, time1, 86400e0);
+       result = time + span->time;
+       TMODULO(result, time1, (double) SECS_PER_DAY);
        if (result < 0)
-               result += 86400;
+               result += SECS_PER_DAY;
 #endif
 
        PG_RETURN_TIMEADT(result);
@@ -1515,93 +1569,22 @@ time_mi_interval(PG_FUNCTION_ARGS)
        TimeADT         result;
 
 #ifdef HAVE_INT64_TIMESTAMP
-       result = (time - span->time);
-       result -= (result / INT64CONST(86400000000) * INT64CONST(86400000000));
+       result = time - span->time;
+       result -= result / USECS_PER_DAY * USECS_PER_DAY;
        if (result < INT64CONST(0))
-               result += INT64CONST(86400000000);
+               result += USECS_PER_DAY;
 #else
        TimeADT         time1;
 
-       result = (time - span->time);
-       TMODULO(result, time1, 86400e0);
+       result = time - span->time;
+       TMODULO(result, time1, (double) SECS_PER_DAY);
        if (result < 0)
-               result += 86400;
+               result += SECS_PER_DAY;
 #endif
 
        PG_RETURN_TIMEADT(result);
 }
 
-/* interval_pl_time()
- * Add time to interval.
- */
-Datum
-interval_pl_time(PG_FUNCTION_ARGS)
-{
-       Datum           span = PG_GETARG_DATUM(0);
-       Datum           time = PG_GETARG_DATUM(1);
-
-       return DirectFunctionCall2(time_pl_interval, time, span);
-}
-
-
-/* time_text()
- * Convert time to text data type.
- */
-Datum
-time_text(PG_FUNCTION_ARGS)
-{
-       /* Input is a Time, but may as well leave it in Datum form */
-       Datum           time = PG_GETARG_DATUM(0);
-       text       *result;
-       char       *str;
-       int                     len;
-
-       str = DatumGetCString(DirectFunctionCall1(time_out, time));
-
-       len = (strlen(str) + VARHDRSZ);
-
-       result = palloc(len);
-
-       VARATT_SIZEP(result) = len;
-       memmove(VARDATA(result), str, (len - VARHDRSZ));
-
-       pfree(str);
-
-       PG_RETURN_TEXT_P(result);
-}
-
-
-/* text_time()
- * Convert text string to time.
- * Text type is not null terminated, so use temporary string
- *     then call the standard input routine.
- */
-Datum
-text_time(PG_FUNCTION_ARGS)
-{
-       text       *str = PG_GETARG_TEXT_P(0);
-       int                     i;
-       char       *sp,
-                          *dp,
-                               dstr[MAXDATELEN + 1];
-
-       if (VARSIZE(str) - VARHDRSZ > MAXDATELEN)
-               ereport(ERROR,
-                               (errcode(ERRCODE_INVALID_DATETIME_FORMAT),
-                                errmsg("invalid input syntax for type time: \"%s\"",
-                                               VARDATA(str))));
-
-       sp = VARDATA(str);
-       dp = dstr;
-       for (i = 0; i < (VARSIZE(str) - VARHDRSZ); i++)
-               *dp++ = *sp++;
-       *dp = '\0';
-
-       return DirectFunctionCall3(time_in,
-                                                          CStringGetDatum(dstr),
-                                                          ObjectIdGetDatum(InvalidOid),
-                                                          Int32GetDatum(-1));
-}
 
 /* time_part()
  * Extract specified field from time type.
@@ -1627,7 +1610,7 @@ time_part(PG_FUNCTION_ARGS)
        if (type == UNITS)
        {
                fsec_t          fsec;
-               struct pg_tm    tt,
+               struct pg_tm tt,
                                   *tm = &tt;
 
                time2tm(time, tm, &fsec);
@@ -1636,26 +1619,25 @@ time_part(PG_FUNCTION_ARGS)
                {
                        case DTK_MICROSEC:
 #ifdef HAVE_INT64_TIMESTAMP
-                               result = ((tm->tm_sec * INT64CONST(1000000)) + fsec);
+                               result = tm->tm_sec * USECS_PER_SEC + fsec;
 #else
-                               result = ((tm->tm_sec + fsec) * 1000000);
+                               result = (tm->tm_sec + fsec) * 1000000;
 #endif
                                break;
 
                        case DTK_MILLISEC:
 #ifdef HAVE_INT64_TIMESTAMP
-                               result = ((tm->tm_sec * INT64CONST(1000))
-                                                 + (fsec / INT64CONST(1000)));
+                               result = tm->tm_sec * INT64CONST(1000) + fsec / INT64CONST(1000);
 #else
-                               result = ((tm->tm_sec + fsec) * 1000);
+                               result = (tm->tm_sec + fsec) * 1000;
 #endif
                                break;
 
                        case DTK_SECOND:
 #ifdef HAVE_INT64_TIMESTAMP
-                               result = (tm->tm_sec + (fsec / INT64CONST(1000000)));
+                               result = tm->tm_sec + fsec / USECS_PER_SEC;
 #else
-                               result = (tm->tm_sec + fsec);
+                               result = tm->tm_sec + fsec;
 #endif
                                break;
 
@@ -1677,20 +1659,21 @@ time_part(PG_FUNCTION_ARGS)
                        case DTK_DECADE:
                        case DTK_CENTURY:
                        case DTK_MILLENNIUM:
+                       case DTK_ISOYEAR:
                        default:
                                ereport(ERROR,
                                                (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
                                                 errmsg("\"time\" units \"%s\" not recognized",
-                                                        DatumGetCString(DirectFunctionCall1(textout,
-                                                                                        PointerGetDatum(units))))));
+                                                               DatumGetCString(DirectFunctionCall1(textout,
+                                                                                                PointerGetDatum(units))))));
 
                                result = 0;
                }
        }
-       else if ((type == RESERV) && (val == DTK_EPOCH))
+       else if (type == RESERV && val == DTK_EPOCH)
        {
 #ifdef HAVE_INT64_TIMESTAMP
-               result = (time / 1000000e0);
+               result = time / 1000000.0;
 #else
                result = time;
 #endif
@@ -1701,7 +1684,7 @@ time_part(PG_FUNCTION_ARGS)
                                (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
                                 errmsg("\"time\" units \"%s\" not recognized",
                                                DatumGetCString(DirectFunctionCall1(textout,
-                                                                                        PointerGetDatum(units))))));
+                                                                                                PointerGetDatum(units))))));
                result = 0;
        }
 
@@ -1720,10 +1703,10 @@ static int
 tm2timetz(struct pg_tm * tm, fsec_t fsec, int tz, TimeTzADT *result)
 {
 #ifdef HAVE_INT64_TIMESTAMP
-       result->time = ((((((tm->tm_hour * 60) + tm->tm_min) * 60) + tm->tm_sec)
-                                        * INT64CONST(1000000)) + fsec);
+       result->time = ((((tm->tm_hour * MINS_PER_HOUR + tm->tm_min) * SECS_PER_MINUTE) + tm->tm_sec) *
+                                       USECS_PER_SEC) + fsec;
 #else
-       result->time = ((((tm->tm_hour * 60) + tm->tm_min) * 60) + tm->tm_sec + fsec);
+       result->time = ((tm->tm_hour * MINS_PER_HOUR + tm->tm_min) * SECS_PER_MINUTE) + tm->tm_sec + fsec;
 #endif
        result->zone = tz;
 
@@ -1741,20 +1724,18 @@ timetz_in(PG_FUNCTION_ARGS)
        int32           typmod = PG_GETARG_INT32(2);
        TimeTzADT  *result;
        fsec_t          fsec;
-       struct pg_tm    tt,
+       struct pg_tm tt,
                           *tm = &tt;
        int                     tz;
        int                     nf;
        int                     dterr;
-       char            lowstr[MAXDATELEN + 1];
+       char            workbuf[MAXDATELEN + 1];
        char       *field[MAXDATEFIELDS];
        int                     dtype;
        int                     ftype[MAXDATEFIELDS];
 
-       if (strlen(str) >= sizeof(lowstr))
-               dterr = DTERR_BAD_FORMAT;
-       else
-               dterr = ParseDateTime(str, lowstr, field, ftype, MAXDATEFIELDS, &nf);
+       dterr = ParseDateTime(str, workbuf, sizeof(workbuf),
+                                                 field, ftype, MAXDATEFIELDS, &nf);
        if (dterr == 0)
                dterr = DecodeTimeOnly(field, ftype, nf, &dtype, tm, &fsec, &tz);
        if (dterr != 0)
@@ -1772,7 +1753,7 @@ timetz_out(PG_FUNCTION_ARGS)
 {
        TimeTzADT  *time = PG_GETARG_TIMETZADT_P(0);
        char       *result;
-       struct pg_tm    tt,
+       struct pg_tm tt,
                           *tm = &tt;
        fsec_t          fsec;
        int                     tz;
@@ -1792,18 +1773,25 @@ Datum
 timetz_recv(PG_FUNCTION_ARGS)
 {
        StringInfo      buf = (StringInfo) PG_GETARG_POINTER(0);
-       TimeTzADT  *time;
 
-       time = (TimeTzADT *) palloc(sizeof(TimeTzADT));
+#ifdef NOT_USED
+       Oid                     typelem = PG_GETARG_OID(1);
+#endif
+       int32           typmod = PG_GETARG_INT32(2);
+       TimeTzADT  *result;
+
+       result = (TimeTzADT *) palloc(sizeof(TimeTzADT));
 
 #ifdef HAVE_INT64_TIMESTAMP
-       time->time = pq_getmsgint64(buf);
+       result->time = pq_getmsgint64(buf);
 #else
-       time->time = pq_getmsgfloat8(buf);
+       result->time = pq_getmsgfloat8(buf);
 #endif
-       time->zone = pq_getmsgint(buf, sizeof(time->zone));
+       result->zone = pq_getmsgint(buf, sizeof(result->zone));
 
-       PG_RETURN_TIMETZADT_P(time);
+       AdjustTimeForTypmod(&(result->time), typmod);
+
+       PG_RETURN_TIMETZADT_P(result);
 }
 
 /*
@@ -1825,6 +1813,22 @@ timetz_send(PG_FUNCTION_ARGS)
        PG_RETURN_BYTEA_P(pq_endtypsend(&buf));
 }
 
+Datum
+timetztypmodin(PG_FUNCTION_ARGS)
+{
+       ArrayType  *ta = PG_GETARG_ARRAYTYPE_P(0);
+
+       PG_RETURN_INT32(anytime_typmodin(true, ta));
+}
+
+Datum
+timetztypmodout(PG_FUNCTION_ARGS)
+{
+       int32           typmod = PG_GETARG_INT32(0);
+
+       PG_RETURN_CSTRING(anytime_typmodout(true, typmod));
+}
+
 
 /* timetz2tm()
  * Convert TIME WITH TIME ZONE data type to POSIX time structure.
@@ -1835,18 +1839,26 @@ timetz2tm(TimeTzADT *time, struct pg_tm * tm, fsec_t *fsec, int *tzp)
 #ifdef HAVE_INT64_TIMESTAMP
        int64           trem = time->time;
 
-       tm->tm_hour = (trem / INT64CONST(3600000000));
-       trem -= (tm->tm_hour * INT64CONST(3600000000));
-       tm->tm_min = (trem / INT64CONST(60000000));
-       trem -= (tm->tm_min * INT64CONST(60000000));
-       tm->tm_sec = (trem / INT64CONST(1000000));
-       *fsec = (trem - (tm->tm_sec * INT64CONST(1000000)));
+       tm->tm_hour = trem / USECS_PER_HOUR;
+       trem -= tm->tm_hour * USECS_PER_HOUR;
+       tm->tm_min = trem / USECS_PER_MINUTE;
+       trem -= tm->tm_min * USECS_PER_MINUTE;
+       tm->tm_sec = trem / USECS_PER_SEC;
+       *fsec = trem - tm->tm_sec * USECS_PER_SEC;
 #else
        double          trem = time->time;
 
-       TMODULO(trem, tm->tm_hour, 3600e0);
-       TMODULO(trem, tm->tm_min, 60e0);
-       TMODULO(trem, tm->tm_sec, 1e0);
+recalc:
+       TMODULO(trem, tm->tm_hour, (double) SECS_PER_HOUR);
+       TMODULO(trem, tm->tm_min, (double) SECS_PER_MINUTE);
+       TMODULO(trem, tm->tm_sec, 1.0);
+       trem = TIMEROUND(trem);
+       /* roundoff may need to propagate to higher-order fields */
+       if (trem >= 1.0)
+       {
+               trem = ceil(time->time);
+               goto recalc;
+       }
        *fsec = trem;
 #endif
 
@@ -1881,12 +1893,20 @@ timetz_scale(PG_FUNCTION_ARGS)
 static int
 timetz_cmp_internal(TimeTzADT *time1, TimeTzADT *time2)
 {
+       /* Primary sort is by true (GMT-equivalent) time */
+#ifdef HAVE_INT64_TIMESTAMP
+       int64           t1,
+                               t2;
+
+       t1 = time1->time + (time1->zone * USECS_PER_SEC);
+       t2 = time2->time + (time2->zone * USECS_PER_SEC);
+#else
        double          t1,
                                t2;
 
-       /* Primary sort is by true (GMT-equivalent) time */
        t1 = time1->time + time1->zone;
        t2 = time2->time + time2->zone;
+#endif
 
        if (t1 > t2)
                return 1;
@@ -1968,20 +1988,27 @@ timetz_cmp(PG_FUNCTION_ARGS)
        PG_RETURN_INT32(timetz_cmp_internal(time1, time2));
 }
 
-/*
- * timetz, being an unusual size, needs a specialized hash function.
- */
 Datum
 timetz_hash(PG_FUNCTION_ARGS)
 {
        TimeTzADT  *key = PG_GETARG_TIMETZADT_P(0);
+       uint32          thash;
 
        /*
-        * Specify hash length as sizeof(double) + sizeof(int4), not as
-        * sizeof(TimeTzADT), so that any garbage pad bytes in the structure
-        * won't be included in the hash!
+        * To avoid any problems with padding bytes in the struct, we figure the
+        * field hashes separately and XOR them.  This also provides a convenient
+        * framework for dealing with the fact that the time field might be either
+        * double or int64.
         */
-       return hash_any((unsigned char *) key, sizeof(key->time) + sizeof(key->zone));
+#ifdef HAVE_INT64_TIMESTAMP
+       thash = DatumGetUInt32(DirectFunctionCall1(hashint8,
+                                                                                          Int64GetDatumFast(key->time)));
+#else
+       thash = DatumGetUInt32(DirectFunctionCall1(hashfloat8,
+                                                                                        Float8GetDatumFast(key->time)));
+#endif
+       thash ^= DatumGetUInt32(hash_uint32(key->zone));
+       PG_RETURN_UINT32(thash);
 }
 
 Datum
@@ -2029,15 +2056,15 @@ timetz_pl_interval(PG_FUNCTION_ARGS)
        result = (TimeTzADT *) palloc(sizeof(TimeTzADT));
 
 #ifdef HAVE_INT64_TIMESTAMP
-       result->time = (time->time + span->time);
-       result->time -= (result->time / INT64CONST(86400000000) * INT64CONST(86400000000));
+       result->time = time->time + span->time;
+       result->time -= result->time / USECS_PER_DAY * USECS_PER_DAY;
        if (result->time < INT64CONST(0))
-               result->time += INT64CONST(86400000000);
+               result->time += USECS_PER_DAY;
 #else
-       result->time = (time->time + span->time);
-       TMODULO(result->time, time1.time, 86400e0);
+       result->time = time->time + span->time;
+       TMODULO(result->time, time1.time, (double) SECS_PER_DAY);
        if (result->time < 0)
-               result->time += 86400;
+               result->time += SECS_PER_DAY;
 #endif
 
        result->zone = time->zone;
@@ -2062,15 +2089,15 @@ timetz_mi_interval(PG_FUNCTION_ARGS)
        result = (TimeTzADT *) palloc(sizeof(TimeTzADT));
 
 #ifdef HAVE_INT64_TIMESTAMP
-       result->time = (time->time - span->time);
-       result->time -= (result->time / INT64CONST(86400000000) * INT64CONST(86400000000));
+       result->time = time->time - span->time;
+       result->time -= result->time / USECS_PER_DAY * USECS_PER_DAY;
        if (result->time < INT64CONST(0))
-               result->time += INT64CONST(86400000000);
+               result->time += USECS_PER_DAY;
 #else
-       result->time = (time->time - span->time);
-       TMODULO(result->time, time1.time, 86400e0);
+       result->time = time->time - span->time;
+       TMODULO(result->time, time1.time, (double) SECS_PER_DAY);
        if (result->time < 0)
-               result->time += 86400;
+               result->time += SECS_PER_DAY;
 #endif
 
        result->zone = time->zone;
@@ -2088,8 +2115,8 @@ Datum
 overlaps_timetz(PG_FUNCTION_ARGS)
 {
        /*
-        * The arguments are TimeTzADT *, but we leave them as generic Datums
-        * for convenience of notation --- and to avoid dereferencing nulls.
+        * The arguments are TimeTzADT *, but we leave them as generic Datums for
+        * convenience of notation --- and to avoid dereferencing nulls.
         */
        Datum           ts1 = PG_GETARG_DATUM(0);
        Datum           te1 = PG_GETARG_DATUM(1);
@@ -2106,9 +2133,9 @@ overlaps_timetz(PG_FUNCTION_ARGS)
        DatumGetBool(DirectFunctionCall2(timetz_lt,t1,t2))
 
        /*
-        * If both endpoints of interval 1 are null, the result is null
-        * (unknown). If just one endpoint is null, take ts1 as the non-null
-        * one. Otherwise, take ts1 as the lesser endpoint.
+        * If both endpoints of interval 1 are null, the result is null (unknown).
+        * If just one endpoint is null, take ts1 as the non-null one. Otherwise,
+        * take ts1 as the lesser endpoint.
         */
        if (ts1IsNull)
        {
@@ -2156,8 +2183,8 @@ overlaps_timetz(PG_FUNCTION_ARGS)
        if (TIMETZ_GT(ts1, ts2))
        {
                /*
-                * This case is ts1 < te2 OR te1 < te2, which may look redundant
-                * but in the presence of nulls it's not quite completely so.
+                * This case is ts1 < te2 OR te1 < te2, which may look redundant but
+                * in the presence of nulls it's not quite completely so.
                 */
                if (te2IsNull)
                        PG_RETURN_NULL();
@@ -2167,8 +2194,8 @@ overlaps_timetz(PG_FUNCTION_ARGS)
                        PG_RETURN_NULL();
 
                /*
-                * If te1 is not null then we had ts1 <= te1 above, and we just
-                * found ts1 >= te2, hence te1 >= te2.
+                * If te1 is not null then we had ts1 <= te1 above, and we just found
+                * ts1 >= te2, hence te1 >= te2.
                 */
                PG_RETURN_BOOL(false);
        }
@@ -2183,8 +2210,8 @@ overlaps_timetz(PG_FUNCTION_ARGS)
                        PG_RETURN_NULL();
 
                /*
-                * If te2 is not null then we had ts2 <= te2 above, and we just
-                * found ts2 >= te1, hence te2 >= te1.
+                * If te2 is not null then we had ts2 <= te2 above, and we just found
+                * ts2 >= te1, hence te2 >= te1.
                 */
                PG_RETURN_BOOL(false);
        }
@@ -2192,8 +2219,7 @@ overlaps_timetz(PG_FUNCTION_ARGS)
        {
                /*
                 * For ts1 = ts2 the spec says te1 <> te2 OR te1 = te2, which is a
-                * rather silly way of saying "true if both are nonnull, else
-                * null".
+                * rather silly way of saying "true if both are nonnull, else null".
                 */
                if (te1IsNull || te2IsNull)
                        PG_RETURN_NULL();
@@ -2223,14 +2249,14 @@ time_timetz(PG_FUNCTION_ARGS)
 {
        TimeADT         time = PG_GETARG_TIMEADT(0);
        TimeTzADT  *result;
-       struct pg_tm    tt,
+       struct pg_tm tt,
                           *tm = &tt;
        fsec_t          fsec;
        int                     tz;
 
        GetCurrentDateTime(tm);
        time2tm(time, tm, &fsec);
-       tz = DetermineLocalTimeZone(tm);
+       tz = DetermineTimeZoneOffset(tm, session_timezone);
 
        result = (TimeTzADT *) palloc(sizeof(TimeTzADT));
 
@@ -2249,7 +2275,7 @@ timestamptz_timetz(PG_FUNCTION_ARGS)
 {
        TimestampTz timestamp = PG_GETARG_TIMESTAMP(0);
        TimeTzADT  *result;
-       struct pg_tm    tt,
+       struct pg_tm tt,
                           *tm = &tt;
        int                     tz;
        fsec_t          fsec;
@@ -2258,7 +2284,7 @@ timestamptz_timetz(PG_FUNCTION_ARGS)
        if (TIMESTAMP_NOT_FINITE(timestamp))
                PG_RETURN_NULL();
 
-       if (timestamp2tm(timestamp, &tz, tm, &fsec, &tzn) != 0)
+       if (timestamp2tm(timestamp, &tz, tm, &fsec, &tzn, NULL) != 0)
                ereport(ERROR,
                                (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
                                 errmsg("timestamp out of range")));
@@ -2285,75 +2311,15 @@ datetimetz_timestamptz(PG_FUNCTION_ARGS)
        TimestampTz result;
 
 #ifdef HAVE_INT64_TIMESTAMP
-       result = (((date * INT64CONST(86400000000)) + time->time)
-                         + (time->zone * INT64CONST(1000000)));
+       result = date * USECS_PER_DAY + time->time + time->zone * USECS_PER_SEC;
 #else
-       result = (((date * 86400.0) + time->time) + time->zone);
+       result = date * (double) SECS_PER_DAY + time->time + time->zone;
 #endif
 
        PG_RETURN_TIMESTAMP(result);
 }
 
 
-/* timetz_text()
- * Convert timetz to text data type.
- */
-Datum
-timetz_text(PG_FUNCTION_ARGS)
-{
-       /* Input is a Timetz, but may as well leave it in Datum form */
-       Datum           timetz = PG_GETARG_DATUM(0);
-       text       *result;
-       char       *str;
-       int                     len;
-
-       str = DatumGetCString(DirectFunctionCall1(timetz_out, timetz));
-
-       len = (strlen(str) + VARHDRSZ);
-
-       result = palloc(len);
-
-       VARATT_SIZEP(result) = len;
-       memmove(VARDATA(result), str, (len - VARHDRSZ));
-
-       pfree(str);
-
-       PG_RETURN_TEXT_P(result);
-}
-
-
-/* text_timetz()
- * Convert text string to timetz.
- * Text type is not null terminated, so use temporary string
- *     then call the standard input routine.
- */
-Datum
-text_timetz(PG_FUNCTION_ARGS)
-{
-       text       *str = PG_GETARG_TEXT_P(0);
-       int                     i;
-       char       *sp,
-                          *dp,
-                               dstr[MAXDATELEN + 1];
-
-       if (VARSIZE(str) - VARHDRSZ > MAXDATELEN)
-               ereport(ERROR,
-                               (errcode(ERRCODE_INVALID_DATETIME_FORMAT),
-                  errmsg("invalid input syntax for type time with time zone: \"%s\"",
-                                 VARDATA(str))));
-
-       sp = VARDATA(str);
-       dp = dstr;
-       for (i = 0; i < (VARSIZE(str) - VARHDRSZ); i++)
-               *dp++ = *sp++;
-       *dp = '\0';
-
-       return DirectFunctionCall3(timetz_in,
-                                                          CStringGetDatum(dstr),
-                                                          ObjectIdGetDatum(InvalidOid),
-                                                          Int32GetDatum(-1));
-}
-
 /* timetz_part()
  * Extract specified field from time type.
  */
@@ -2380,7 +2346,7 @@ timetz_part(PG_FUNCTION_ARGS)
                double          dummy;
                int                     tz;
                fsec_t          fsec;
-               struct pg_tm    tt,
+               struct pg_tm tt,
                                   *tm = &tt;
 
                timetz2tm(time, tm, &fsec, &tz);
@@ -2393,37 +2359,36 @@ timetz_part(PG_FUNCTION_ARGS)
 
                        case DTK_TZ_MINUTE:
                                result = -tz;
-                               result /= 60;
-                               FMODULO(result, dummy, 60e0);
+                               result /= SECS_PER_MINUTE;
+                               FMODULO(result, dummy, (double) SECS_PER_MINUTE);
                                break;
 
                        case DTK_TZ_HOUR:
                                dummy = -tz;
-                               FMODULO(dummy, result, 3600e0);
+                               FMODULO(dummy, result, (double) SECS_PER_HOUR);
                                break;
 
                        case DTK_MICROSEC:
 #ifdef HAVE_INT64_TIMESTAMP
-                               result = ((tm->tm_sec * INT64CONST(1000000)) + fsec);
+                               result = tm->tm_sec * USECS_PER_SEC + fsec;
 #else
-                               result = ((tm->tm_sec + fsec) * 1000000);
+                               result = (tm->tm_sec + fsec) * 1000000;
 #endif
                                break;
 
                        case DTK_MILLISEC:
 #ifdef HAVE_INT64_TIMESTAMP
-                               result = ((tm->tm_sec * INT64CONST(1000))
-                                                 + (fsec / INT64CONST(1000)));
+                               result = tm->tm_sec * INT64CONST(1000) + fsec / INT64CONST(1000);
 #else
-                               result = ((tm->tm_sec + fsec) * 1000);
+                               result = (tm->tm_sec + fsec) * 1000;
 #endif
                                break;
 
                        case DTK_SECOND:
 #ifdef HAVE_INT64_TIMESTAMP
-                               result = (tm->tm_sec + (fsec / INT64CONST(1000000)));
+                               result = tm->tm_sec + fsec / USECS_PER_SEC;
 #else
-                               result = (tm->tm_sec + fsec);
+                               result = tm->tm_sec + fsec;
 #endif
                                break;
 
@@ -2445,19 +2410,19 @@ timetz_part(PG_FUNCTION_ARGS)
                        default:
                                ereport(ERROR,
                                                (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
-                                                errmsg("\"time with time zone\" units \"%s\" not recognized",
-                                                        DatumGetCString(DirectFunctionCall1(textout,
-                                                                                        PointerGetDatum(units))))));
+                               errmsg("\"time with time zone\" units \"%s\" not recognized",
+                                          DatumGetCString(DirectFunctionCall1(textout,
+                                                                                                PointerGetDatum(units))))));
 
                                result = 0;
                }
        }
-       else if ((type == RESERV) && (val == DTK_EPOCH))
+       else if (type == RESERV && val == DTK_EPOCH)
        {
 #ifdef HAVE_INT64_TIMESTAMP
-               result = ((time->time / 1000000e0) - time->zone);
+               result = time->time / 1000000.0 + time->zone;
 #else
-               result = (time->time - time->zone);
+               result = time->time + time->zone;
 #endif
        }
        else
@@ -2466,7 +2431,7 @@ timetz_part(PG_FUNCTION_ARGS)
                                (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
                                 errmsg("\"time with time zone\" units \"%s\" not recognized",
                                                DatumGetCString(DirectFunctionCall1(textout,
-                                                                                        PointerGetDatum(units))))));
+                                                                                                PointerGetDatum(units))))));
 
                result = 0;
        }
@@ -2476,56 +2441,80 @@ timetz_part(PG_FUNCTION_ARGS)
 
 /* timetz_zone()
  * Encode time with time zone type with specified time zone.
+ * Applies DST rules as of the current date.
  */
 Datum
 timetz_zone(PG_FUNCTION_ARGS)
 {
        text       *zone = PG_GETARG_TEXT_P(0);
-       TimeTzADT  *time = PG_GETARG_TIMETZADT_P(1);
+       TimeTzADT  *t = PG_GETARG_TIMETZADT_P(1);
        TimeTzADT  *result;
        int                     tz;
-       int                     type,
-                               val;
-       char       *lowzone;
+       char            tzname[TZ_STRLEN_MAX + 1];
+       int                     len;
+       pg_tz      *tzp;
 
-       lowzone = downcase_truncate_identifier(VARDATA(zone),
-                                                                                  VARSIZE(zone) - VARHDRSZ,
-                                                                                  false);
+       /*
+        * Look up the requested timezone.      First we look in the timezone database
+        * (to handle cases like "America/New_York"), and if that fails, we look
+        * in the date token table (to handle cases like "EST").
+        */
+       len = Min(VARSIZE(zone) - VARHDRSZ, TZ_STRLEN_MAX);
+       memcpy(tzname, VARDATA(zone), len);
+       tzname[len] = '\0';
+       tzp = pg_tzset(tzname);
+       if (tzp)
+       {
+               /* Get the offset-from-GMT that is valid today for the selected zone */
+               pg_time_t       now;
+               struct pg_tm *tm;
 
-       type = DecodeSpecial(0, lowzone, &val);
+               now = time(NULL);
+               tm = pg_localtime(&now, tzp);
+               tz = -tm->tm_gmtoff;
+       }
+       else
+       {
+               char       *lowzone;
+               int                     type,
+                                       val;
+
+               lowzone = downcase_truncate_identifier(VARDATA(zone),
+                                                                                          VARSIZE(zone) - VARHDRSZ,
+                                                                                          false);
+               type = DecodeSpecial(0, lowzone, &val);
+
+               if (type == TZ || type == DTZ)
+                       tz = val * 60;
+               else
+               {
+                       ereport(ERROR,
+                                       (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
+                                        errmsg("time zone \"%s\" not recognized", tzname)));
+                       tz = 0;                         /* keep compiler quiet */
+               }
+       }
 
        result = (TimeTzADT *) palloc(sizeof(TimeTzADT));
 
-       if ((type == TZ) || (type == DTZ))
-       {
-               tz = val * 60;
 #ifdef HAVE_INT64_TIMESTAMP
-               result->time = time->time + ((time->zone - tz) * INT64CONST(1000000));
-               while (result->time < INT64CONST(0))
-                       result->time += INT64CONST(86400000000);
-               while (result->time >= INT64CONST(86400000000))
-                       result->time -= INT64CONST(86400000000);
+       result->time = t->time + (t->zone - tz) * USECS_PER_SEC;
+       while (result->time < INT64CONST(0))
+               result->time += USECS_PER_DAY;
+       while (result->time >= USECS_PER_DAY)
+               result->time -= USECS_PER_DAY;
 #else
-               result->time = time->time + (time->zone - tz);
-               while (result->time < 0)
-                       result->time += 86400;
-               while (result->time >= 86400)
-                       result->time -= 86400;
+       result->time = t->time + (t->zone - tz);
+       while (result->time < 0)
+               result->time += SECS_PER_DAY;
+       while (result->time >= SECS_PER_DAY)
+               result->time -= SECS_PER_DAY;
 #endif
 
-               result->zone = tz;
-       }
-       else
-       {
-               ereport(ERROR,
-                               (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
-                                errmsg("time zone \"%s\" not recognized", lowzone)));
-
-               PG_RETURN_NULL();
-       }
+       result->zone = tz;
 
        PG_RETURN_TIMETZADT_P(result);
-}      /* timetz_zone() */
+}
 
 /* timetz_izone()
  * Encode time with time zone type with specified time interval as time zone.
@@ -2543,10 +2532,10 @@ timetz_izone(PG_FUNCTION_ARGS)
                                (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
                                 errmsg("\"interval\" time zone \"%s\" not valid",
                                                DatumGetCString(DirectFunctionCall1(interval_out,
-                                                                                         PointerGetDatum(zone))))));
+                                                                                                 PointerGetDatum(zone))))));
 
 #ifdef HAVE_INT64_TIMESTAMP
-       tz = -(zone->time / INT64CONST(1000000));
+       tz = -(zone->time / USECS_PER_SEC);
 #else
        tz = -(zone->time);
 #endif
@@ -2554,20 +2543,20 @@ timetz_izone(PG_FUNCTION_ARGS)
        result = (TimeTzADT *) palloc(sizeof(TimeTzADT));
 
 #ifdef HAVE_INT64_TIMESTAMP
-       result->time = time->time + ((time->zone - tz) * INT64CONST(1000000));
+       result->time = time->time + (time->zone - tz) * USECS_PER_SEC;
        while (result->time < INT64CONST(0))
-               result->time += INT64CONST(86400000000);
-       while (result->time >= INT64CONST(86400000000))
-               result->time -= INT64CONST(86400000000);
+               result->time += USECS_PER_DAY;
+       while (result->time >= USECS_PER_DAY)
+               result->time -= USECS_PER_DAY;
 #else
        result->time = time->time + (time->zone - tz);
        while (result->time < 0)
-               result->time += 86400;
-       while (result->time >= 86400)
-               result->time -= 86400;
+               result->time += SECS_PER_DAY;
+       while (result->time >= SECS_PER_DAY)
+               result->time -= SECS_PER_DAY;
 #endif
 
        result->zone = tz;
 
        PG_RETURN_TIMETZADT_P(result);
-}      /* timetz_izone() */
+}