1 /*-------------------------------------------------------------------------
4 * Support functions for date/time types.
6 * Portions Copyright (c) 1996-2006, PostgreSQL Global Development Group
7 * Portions Copyright (c) 1994, Regents of the University of California
11 * $PostgreSQL: pgsql/src/backend/utils/adt/datetime.c,v 1.174 2006/10/18 16:43:13 tgl Exp $
13 *-------------------------------------------------------------------------
22 #include "access/heapam.h"
23 #include "access/xact.h"
24 #include "catalog/pg_type.h"
26 #include "miscadmin.h"
27 #include "utils/builtins.h"
28 #include "utils/datetime.h"
29 #include "utils/memutils.h"
30 #include "utils/tzparser.h"
33 static int DecodeNumber(int flen, char *field, bool haveTextMonth,
34 int fmask, int *tmask,
35 struct pg_tm * tm, fsec_t *fsec, int *is2digits);
36 static int DecodeNumberField(int len, char *str,
37 int fmask, int *tmask,
38 struct pg_tm * tm, fsec_t *fsec, int *is2digits);
39 static int DecodeTime(char *str, int fmask, int *tmask,
40 struct pg_tm * tm, fsec_t *fsec);
41 static int DecodeTimezone(char *str, int *tzp);
42 static const datetkn *datebsearch(const char *key, const datetkn *base, int nel);
43 static int DecodeDate(char *str, int fmask, int *tmask, struct pg_tm * tm);
44 static void TrimTrailingZeros(char *str);
47 const int day_tab[2][13] =
49 {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31, 0},
50 {31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31, 0}
53 char *months[] = {"Jan", "Feb", "Mar", "Apr", "May", "Jun",
54 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec", NULL};
56 char *days[] = {"Sunday", "Monday", "Tuesday", "Wednesday",
57 "Thursday", "Friday", "Saturday", NULL};
60 /*****************************************************************************
62 *****************************************************************************/
65 * Definitions for squeezing values into "value"
66 * We set aside a high bit for a sign, and scale the timezone offsets
67 * in minutes by a factor of 15 (so can represent quarter-hour increments).
69 #define ABS_SIGNBIT ((char) 0200)
70 #define VALMASK ((char) 0177)
72 #define NEG(n) ((n)|ABS_SIGNBIT)
73 #define SIGNEDCHAR(c) ((c)&ABS_SIGNBIT? -((c)&VALMASK): (c))
74 #define FROMVAL(tp) (-SIGNEDCHAR((tp)->value) * 15) /* uncompress */
75 #define TOVAL(tp, v) ((tp)->value = ((v) < 0? NEG((-(v))/15): POS(v)/15))
78 * datetktbl holds date/time keywords.
80 * Note that this table must be strictly alphabetically ordered to allow an
81 * O(ln(N)) search algorithm to be used.
83 * The text field is NOT guaranteed to be NULL-terminated.
85 * To keep this table reasonably small, we divide the lexval for TZ and DTZ
86 * entries by 15 (so they are on 15 minute boundaries) and truncate the text
87 * field at TOKMAXLEN characters.
88 * Formerly, we divided by 10 rather than 15 but there are a few time zones
89 * which are 30 or 45 minutes away from an even hour, most are on an hour
90 * boundary, and none on other boundaries.
92 * The static table contains no TZ or DTZ entries, rather those are loaded
93 * from configuration files and stored in timezonetktbl, which has the same
94 * format as the static datetktbl.
96 static datetkn *timezonetktbl = NULL;
98 static int sztimezonetktbl = 0;
100 static const datetkn datetktbl[] = {
101 /* text, token, lexval */
102 {EARLY, RESERV, DTK_EARLY}, /* "-infinity" reserved for "early time" */
103 {"abstime", IGNORE_DTF, 0}, /* for pre-v6.1 "Invalid Abstime" */
104 {DA_D, ADBC, AD}, /* "ad" for years > 0 */
105 {"allballs", RESERV, DTK_ZULU}, /* 00:00:00 */
109 {"at", IGNORE_DTF, 0}, /* "at" (throwaway) */
111 {"august", MONTH, 8},
112 {DB_C, ADBC, BC}, /* "bc" for years <= 0 */
113 {DCURRENT, RESERV, DTK_CURRENT}, /* "current" is always now */
114 {"d", UNITS, DTK_DAY}, /* "day of month" for ISO input */
116 {"december", MONTH, 12},
117 {"dow", RESERV, DTK_DOW}, /* day of week */
118 {"doy", RESERV, DTK_DOY}, /* day of year */
120 {EPOCH, RESERV, DTK_EPOCH}, /* "epoch" reserved for system epoch time */
122 {"february", MONTH, 2},
125 {"h", UNITS, DTK_HOUR}, /* "hour" */
126 {LATE, RESERV, DTK_LATE}, /* "infinity" reserved for "late time" */
127 {INVALID, RESERV, DTK_INVALID}, /* "invalid" reserved for bad time */
128 {"j", UNITS, DTK_JULIAN},
130 {"january", MONTH, 1},
131 {"jd", UNITS, DTK_JULIAN},
133 {"julian", UNITS, DTK_JULIAN},
137 {"m", UNITS, DTK_MONTH}, /* "month" for ISO input */
141 {"mm", UNITS, DTK_MINUTE}, /* "minute" for ISO input */
145 {"november", MONTH, 11},
146 {NOW, RESERV, DTK_NOW}, /* current transaction time */
148 {"october", MONTH, 10},
149 {"on", IGNORE_DTF, 0}, /* "on" (throwaway) */
151 {"s", UNITS, DTK_SECOND}, /* "seconds" for ISO input */
153 {"saturday", DOW, 6},
156 {"september", MONTH, 9},
159 {"t", ISOTIME, DTK_TIME}, /* Filler for ISO time fields */
163 {"thursday", DOW, 4},
164 {TODAY, RESERV, DTK_TODAY}, /* midnight */
165 {TOMORROW, RESERV, DTK_TOMORROW}, /* tomorrow midnight */
169 {"undefined", RESERV, DTK_INVALID}, /* pre-v6.1 invalid time */
171 {"wednesday", DOW, 3},
173 {"y", UNITS, DTK_YEAR}, /* "year" for ISO input */
174 {YESTERDAY, RESERV, DTK_YESTERDAY} /* yesterday midnight */
177 static int szdatetktbl = sizeof datetktbl / sizeof datetktbl[0];
179 static datetkn deltatktbl[] = {
180 /* text, token, lexval */
181 {"@", IGNORE_DTF, 0}, /* postgres relative prefix */
182 {DAGO, AGO, 0}, /* "ago" indicates negative time offset */
183 {"c", UNITS, DTK_CENTURY}, /* "century" relative */
184 {"cent", UNITS, DTK_CENTURY}, /* "century" relative */
185 {"centuries", UNITS, DTK_CENTURY}, /* "centuries" relative */
186 {DCENTURY, UNITS, DTK_CENTURY}, /* "century" relative */
187 {"d", UNITS, DTK_DAY}, /* "day" relative */
188 {DDAY, UNITS, DTK_DAY}, /* "day" relative */
189 {"days", UNITS, DTK_DAY}, /* "days" relative */
190 {"dec", UNITS, DTK_DECADE}, /* "decade" relative */
191 {DDECADE, UNITS, DTK_DECADE}, /* "decade" relative */
192 {"decades", UNITS, DTK_DECADE}, /* "decades" relative */
193 {"decs", UNITS, DTK_DECADE}, /* "decades" relative */
194 {"h", UNITS, DTK_HOUR}, /* "hour" relative */
195 {DHOUR, UNITS, DTK_HOUR}, /* "hour" relative */
196 {"hours", UNITS, DTK_HOUR}, /* "hours" relative */
197 {"hr", UNITS, DTK_HOUR}, /* "hour" relative */
198 {"hrs", UNITS, DTK_HOUR}, /* "hours" relative */
199 {INVALID, RESERV, DTK_INVALID}, /* reserved for invalid time */
200 {"m", UNITS, DTK_MINUTE}, /* "minute" relative */
201 {"microsecon", UNITS, DTK_MICROSEC}, /* "microsecond" relative */
202 {"mil", UNITS, DTK_MILLENNIUM}, /* "millennium" relative */
203 {"millennia", UNITS, DTK_MILLENNIUM}, /* "millennia" relative */
204 {DMILLENNIUM, UNITS, DTK_MILLENNIUM}, /* "millennium" relative */
205 {"millisecon", UNITS, DTK_MILLISEC}, /* relative */
206 {"mils", UNITS, DTK_MILLENNIUM}, /* "millennia" relative */
207 {"min", UNITS, DTK_MINUTE}, /* "minute" relative */
208 {"mins", UNITS, DTK_MINUTE}, /* "minutes" relative */
209 {DMINUTE, UNITS, DTK_MINUTE}, /* "minute" relative */
210 {"minutes", UNITS, DTK_MINUTE}, /* "minutes" relative */
211 {"mon", UNITS, DTK_MONTH}, /* "months" relative */
212 {"mons", UNITS, DTK_MONTH}, /* "months" relative */
213 {DMONTH, UNITS, DTK_MONTH}, /* "month" relative */
214 {"months", UNITS, DTK_MONTH},
215 {"ms", UNITS, DTK_MILLISEC},
216 {"msec", UNITS, DTK_MILLISEC},
217 {DMILLISEC, UNITS, DTK_MILLISEC},
218 {"mseconds", UNITS, DTK_MILLISEC},
219 {"msecs", UNITS, DTK_MILLISEC},
220 {"qtr", UNITS, DTK_QUARTER}, /* "quarter" relative */
221 {DQUARTER, UNITS, DTK_QUARTER}, /* "quarter" relative */
222 {"reltime", IGNORE_DTF, 0}, /* pre-v6.1 "Undefined Reltime" */
223 {"s", UNITS, DTK_SECOND},
224 {"sec", UNITS, DTK_SECOND},
225 {DSECOND, UNITS, DTK_SECOND},
226 {"seconds", UNITS, DTK_SECOND},
227 {"secs", UNITS, DTK_SECOND},
228 {DTIMEZONE, UNITS, DTK_TZ}, /* "timezone" time offset */
229 {"timezone_h", UNITS, DTK_TZ_HOUR}, /* timezone hour units */
230 {"timezone_m", UNITS, DTK_TZ_MINUTE}, /* timezone minutes units */
231 {"undefined", RESERV, DTK_INVALID}, /* pre-v6.1 invalid time */
232 {"us", UNITS, DTK_MICROSEC}, /* "microsecond" relative */
233 {"usec", UNITS, DTK_MICROSEC}, /* "microsecond" relative */
234 {DMICROSEC, UNITS, DTK_MICROSEC}, /* "microsecond" relative */
235 {"useconds", UNITS, DTK_MICROSEC}, /* "microseconds" relative */
236 {"usecs", UNITS, DTK_MICROSEC}, /* "microseconds" relative */
237 {"w", UNITS, DTK_WEEK}, /* "week" relative */
238 {DWEEK, UNITS, DTK_WEEK}, /* "week" relative */
239 {"weeks", UNITS, DTK_WEEK}, /* "weeks" relative */
240 {"y", UNITS, DTK_YEAR}, /* "year" relative */
241 {DYEAR, UNITS, DTK_YEAR}, /* "year" relative */
242 {"years", UNITS, DTK_YEAR}, /* "years" relative */
243 {"yr", UNITS, DTK_YEAR}, /* "year" relative */
244 {"yrs", UNITS, DTK_YEAR} /* "years" relative */
247 static int szdeltatktbl = sizeof deltatktbl / sizeof deltatktbl[0];
249 static const datetkn *datecache[MAXDATEFIELDS] = {NULL};
251 static const datetkn *deltacache[MAXDATEFIELDS] = {NULL};
255 * Calendar time to Julian date conversions.
256 * Julian date is commonly used in astronomical applications,
257 * since it is numerically accurate and computationally simple.
258 * The algorithms here will accurately convert between Julian day
259 * and calendar date for all non-negative Julian days
260 * (i.e. from Nov 24, -4713 on).
262 * These routines will be used by other date/time packages
265 * Rewritten to eliminate overflow problems. This now allows the
266 * routines to work correctly for all Julian day counts from
267 * 0 to 2147483647 (Nov 24, -4713 to Jun 3, 5874898) assuming
268 * a 32-bit integer. Longer types should also work to the limits
269 * of their precision.
273 date2j(int y, int m, int d)
290 julian = y * 365 - 32167;
291 julian += y / 4 - century + century / 4;
292 julian += 7834 * m / 256 + d;
298 j2date(int jd, int *year, int *month, int *day)
307 quad = julian / 146097;
308 extra = (julian - quad * 146097) * 4 + 3;
309 julian += 60 + quad * 3 + extra / 146097;
310 quad = julian / 1461;
311 julian -= quad * 1461;
312 y = julian * 4 / 1461;
313 julian = ((y != 0) ? ((julian + 305) % 365) : ((julian + 306) % 366))
317 quad = julian * 2141 / 65536;
318 *day = julian - 7834 * quad / 256;
319 *month = (quad + 10) % 12 + 1;
326 * j2day - convert Julian date to day-of-week (0..6 == Sun..Sat)
328 * Note: various places use the locution j2day(date - 1) to produce a
329 * result according to the convention 0..6 = Mon..Sun. This is a bit of
330 * a crock, but will work as long as the computation here is just a modulo.
347 * GetCurrentDateTime()
349 * Get the transaction start time ("now()") broken down as a struct pg_tm.
352 GetCurrentDateTime(struct pg_tm * tm)
357 timestamp2tm(GetCurrentTransactionStartTimestamp(), &tz, tm, &fsec,
359 /* Note: don't pass NULL tzp to timestamp2tm; affects behavior */
363 * GetCurrentTimeUsec()
365 * Get the transaction start time ("now()") broken down as a struct pg_tm,
366 * including fractional seconds and timezone offset.
369 GetCurrentTimeUsec(struct pg_tm * tm, fsec_t *fsec, int *tzp)
373 timestamp2tm(GetCurrentTransactionStartTimestamp(), &tz, tm, fsec,
375 /* Note: don't pass NULL tzp to timestamp2tm; affects behavior */
381 /* TrimTrailingZeros()
382 * ... resulting from printing numbers with full precision.
385 TrimTrailingZeros(char *str)
387 int len = strlen(str);
390 /* chop off trailing one to cope with interval rounding */
391 if (strcmp(str + len - 4, "0001") == 0)
398 /* chop off trailing zeros... but leave at least 2 fractional digits */
399 while (*(str + len - 1) == '0' && *(str + len - 3) != '.')
407 * Break string into tokens based on a date/time context.
408 * Returns 0 if successful, DTERR code if bogus input detected.
410 * timestr - the input string
411 * workbuf - workspace for field string storage. This must be
412 * larger than the largest legal input for this datetime type --
413 * some additional space will be needed to NUL terminate fields.
414 * buflen - the size of workbuf
415 * field[] - pointers to field strings are returned in this array
416 * ftype[] - field type indicators are returned in this array
417 * maxfields - dimensions of the above two arrays
418 * *numfields - set to the actual number of fields detected
420 * The fields extracted from the input are stored as separate,
421 * null-terminated strings in the workspace at workbuf. Any text is
422 * converted to lower case.
424 * Several field types are assigned:
425 * DTK_NUMBER - digits and (possibly) a decimal point
426 * DTK_DATE - digits and two delimiters, or digits and text
427 * DTK_TIME - digits, colon delimiters, and possibly a decimal point
428 * DTK_STRING - text (no digits or punctuation)
429 * DTK_SPECIAL - leading "+" or "-" followed by text
430 * DTK_TZ - leading "+" or "-" followed by digits (also eats ':' or '.')
432 * Note that some field types can hold unexpected items:
433 * DTK_NUMBER can hold date fields (yy.ddd)
434 * DTK_STRING can hold months (January) and time zones (PST)
435 * DTK_DATE can hold time zone names (America/New_York, GMT-8)
438 ParseDateTime(const char *timestr, char *workbuf, size_t buflen,
439 char **field, int *ftype, int maxfields, int *numfields)
442 const char *cp = timestr;
443 char *bufp = workbuf;
444 const char *bufend = workbuf + buflen;
447 * Set the character pointed-to by "bufptr" to "newchar", and increment
448 * "bufptr". "end" gives the end of the buffer -- we return an error if
449 * there is no space left to append a character to the buffer. Note that
450 * "bufptr" is evaluated twice.
452 #define APPEND_CHAR(bufptr, end, newchar) \
455 if (((bufptr) + 1) >= (end)) \
456 return DTERR_BAD_FORMAT; \
457 *(bufptr)++ = newchar; \
460 /* outer loop through fields */
463 /* Ignore spaces between fields */
464 if (isspace((unsigned char) *cp))
470 /* Record start of current field */
472 return DTERR_BAD_FORMAT;
475 /* leading digit? then date or time */
476 if (isdigit((unsigned char) *cp))
478 APPEND_CHAR(bufp, bufend, *cp++);
479 while (isdigit((unsigned char) *cp))
480 APPEND_CHAR(bufp, bufend, *cp++);
485 ftype[nf] = DTK_TIME;
486 APPEND_CHAR(bufp, bufend, *cp++);
487 while (isdigit((unsigned char) *cp) ||
488 (*cp == ':') || (*cp == '.'))
489 APPEND_CHAR(bufp, bufend, *cp++);
491 /* date field? allow embedded text month */
492 else if (*cp == '-' || *cp == '/' || *cp == '.')
494 /* save delimiting character to use later */
497 APPEND_CHAR(bufp, bufend, *cp++);
498 /* second field is all digits? then no embedded text month */
499 if (isdigit((unsigned char) *cp))
501 ftype[nf] = ((delim == '.') ? DTK_NUMBER : DTK_DATE);
502 while (isdigit((unsigned char) *cp))
503 APPEND_CHAR(bufp, bufend, *cp++);
506 * insist that the delimiters match to get a three-field
511 ftype[nf] = DTK_DATE;
512 APPEND_CHAR(bufp, bufend, *cp++);
513 while (isdigit((unsigned char) *cp) || *cp == delim)
514 APPEND_CHAR(bufp, bufend, *cp++);
519 ftype[nf] = DTK_DATE;
520 while (isalnum((unsigned char) *cp) || *cp == delim)
521 APPEND_CHAR(bufp, bufend, pg_tolower((unsigned char) *cp++));
526 * otherwise, number only and will determine year, month, day, or
527 * concatenated fields later...
530 ftype[nf] = DTK_NUMBER;
532 /* Leading decimal point? Then fractional seconds... */
535 APPEND_CHAR(bufp, bufend, *cp++);
536 while (isdigit((unsigned char) *cp))
537 APPEND_CHAR(bufp, bufend, *cp++);
539 ftype[nf] = DTK_NUMBER;
543 * text? then date string, month, day of week, special, or timezone
545 else if (isalpha((unsigned char) *cp))
549 ftype[nf] = DTK_STRING;
550 APPEND_CHAR(bufp, bufend, pg_tolower((unsigned char) *cp++));
551 while (isalpha((unsigned char) *cp))
552 APPEND_CHAR(bufp, bufend, pg_tolower((unsigned char) *cp++));
555 * Dates can have embedded '-', '/', or '.' separators. It could
556 * also be a timezone name containing embedded '/', '+', '-',
557 * '_', or ':' (but '_' or ':' can't be the first punctuation).
558 * If the next character is a digit or '+', we need to check
559 * whether what we have so far is a recognized non-timezone
560 * keyword --- if so, don't believe that this is the start of
564 if (*cp == '-' || *cp == '/' || *cp == '.')
566 else if (*cp == '+' || isdigit((unsigned char) *cp))
568 *bufp = '\0'; /* null-terminate current field value */
569 /* we need search only the core token table, not TZ names */
570 if (datebsearch(field[nf], datetktbl, szdatetktbl) == NULL)
575 ftype[nf] = DTK_DATE;
578 APPEND_CHAR(bufp, bufend, pg_tolower((unsigned char) *cp++));
579 } while (*cp == '+' || *cp == '-' ||
580 *cp == '/' || *cp == '_' ||
581 *cp == '.' || *cp == ':' ||
582 isalnum((unsigned char) *cp));
585 /* sign? then special or numeric timezone */
586 else if (*cp == '+' || *cp == '-')
588 APPEND_CHAR(bufp, bufend, *cp++);
589 /* soak up leading whitespace */
590 while (isspace((unsigned char) *cp))
592 /* numeric timezone? */
593 if (isdigit((unsigned char) *cp))
596 APPEND_CHAR(bufp, bufend, *cp++);
597 while (isdigit((unsigned char) *cp) ||
598 *cp == ':' || *cp == '.')
599 APPEND_CHAR(bufp, bufend, *cp++);
602 else if (isalpha((unsigned char) *cp))
604 ftype[nf] = DTK_SPECIAL;
605 APPEND_CHAR(bufp, bufend, pg_tolower((unsigned char) *cp++));
606 while (isalpha((unsigned char) *cp))
607 APPEND_CHAR(bufp, bufend, pg_tolower((unsigned char) *cp++));
609 /* otherwise something wrong... */
611 return DTERR_BAD_FORMAT;
613 /* ignore other punctuation but use as delimiter */
614 else if (ispunct((unsigned char) *cp))
619 /* otherwise, something is not right... */
621 return DTERR_BAD_FORMAT;
623 /* force in a delimiter after each field */
635 * Interpret previously parsed fields for general date and time.
636 * Return 0 if full date, 1 if only time, and negative DTERR code if problems.
637 * (Currently, all callers treat 1 as an error return too.)
639 * External format(s):
640 * "<weekday> <month>-<day>-<year> <hour>:<minute>:<second>"
641 * "Fri Feb-7-1997 15:23:27"
642 * "Feb-7-1997 15:23:27"
643 * "2-7-1997 15:23:27"
644 * "1997-2-7 15:23:27"
645 * "1997.038 15:23:27" (day of year 1-366)
646 * Also supports input in compact time:
649 * "20011225T040506.789-07"
651 * Use the system-provided functions to get the current time zone
652 * if not specified in the input string.
653 * If the date is outside the time_t system-supported time range,
654 * then assume UTC time zone. - thomas 1997-05-27
657 DecodeDateTime(char **field, int *ftype, int nf,
658 int *dtype, struct pg_tm * tm, fsec_t *fsec, int *tzp)
663 int ptype = 0; /* "prefix type" for ISO y2001m02d04 format */
668 bool haveTextMonth = FALSE;
669 int is2digits = FALSE;
671 pg_tz *namedTz = NULL;
674 * We'll insist on at least all of the date fields, but initialize the
675 * remaining fields in case they are not set later...
682 /* don't know daylight savings time status apriori */
687 for (i = 0; i < nf; i++)
693 * Integral julian day with attached time zone?
694 * All other forms with JD will be separated into
695 * distinct fields, so we handle just this case here.
697 if (ptype == DTK_JULIAN)
703 return DTERR_BAD_FORMAT;
706 val = strtol(field[i], &cp, 10);
708 return DTERR_FIELD_OVERFLOW;
710 j2date(val, &tm->tm_year, &tm->tm_mon, &tm->tm_mday);
711 /* Get the time zone from the end of the string */
712 dterr = DecodeTimezone(cp, tzp);
716 tmask = DTK_DATE_M | DTK_TIME_M | DTK_M(TZ);
721 * Already have a date? Then this might be a time zone name
722 * with embedded punctuation (e.g. "America/New_York") or
723 * a run-together time with trailing time zone (e.g. hhmmss-zz).
724 * - thomas 2001-12-25
726 else if ((fmask & DTK_DATE_M) == DTK_DATE_M || ptype != 0)
728 /* No time zone accepted? Then quit... */
730 return DTERR_BAD_FORMAT;
732 if (isdigit((unsigned char) *field[i]) || ptype != 0)
738 /* Sanity check; should not fail this test */
739 if (ptype != DTK_TIME)
740 return DTERR_BAD_FORMAT;
745 * Starts with a digit but we already have a time
746 * field? Then we are in trouble with a date and time
749 if ((fmask & DTK_TIME_M) == DTK_TIME_M)
750 return DTERR_BAD_FORMAT;
752 if ((cp = strchr(field[i], '-')) == NULL)
753 return DTERR_BAD_FORMAT;
755 /* Get the time zone from the end of the string */
756 dterr = DecodeTimezone(cp, tzp);
762 * Then read the rest of the field as a concatenated
765 dterr = DecodeNumberField(strlen(field[i]), field[i],
773 * modify tmask after returning from
774 * DecodeNumberField()
780 namedTz = pg_tzset(field[i]);
784 * We should return an error code instead of
785 * ereport'ing directly, but then there is no
786 * way to report the bad time zone name.
789 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
790 errmsg("time zone \"%s\" not recognized",
793 /* we'll apply the zone setting below */
799 dterr = DecodeDate(field[i], fmask, &tmask, tm);
806 dterr = DecodeTime(field[i], fmask, &tmask, tm, fsec);
811 * Check upper limit on hours; other limits checked in
814 /* test for > 24:00:00 */
815 if (tm->tm_hour > 24 ||
816 (tm->tm_hour == 24 && (tm->tm_min > 0 || tm->tm_sec > 0)))
817 return DTERR_FIELD_OVERFLOW;
825 return DTERR_BAD_FORMAT;
827 dterr = DecodeTimezone(field[i], &tz);
838 * Was this an "ISO date" with embedded field labels? An
839 * example is "y2001m02d04" - thomas 2001-02-04
847 val = strtol(field[i], &cp, 10);
849 return DTERR_FIELD_OVERFLOW;
852 * only a few kinds are allowed to have an embedded
863 return DTERR_BAD_FORMAT;
866 else if (*cp != '\0')
867 return DTERR_BAD_FORMAT;
879 * already have a month and hour? then assume
882 if ((fmask & DTK_M(MONTH)) != 0 &&
883 (fmask & DTK_M(HOUR)) != 0)
886 tmask = DTK_M(MINUTE);
891 tmask = DTK_M(MONTH);
907 tmask = DTK_M(MINUTE);
912 tmask = DTK_M(SECOND);
917 frac = strtod(cp, &cp);
919 return DTERR_BAD_FORMAT;
920 #ifdef HAVE_INT64_TIMESTAMP
921 *fsec = rint(frac * 1000000);
930 dterr = DecodeTimezone(field[i], tzp);
937 * previous field was a label for "julian date"?
940 j2date(val, &tm->tm_year, &tm->tm_mon, &tm->tm_mday);
941 /* fractional Julian Day? */
946 time = strtod(cp, &cp);
948 return DTERR_BAD_FORMAT;
951 #ifdef HAVE_INT64_TIMESTAMP
952 dt2time(time * USECS_PER_DAY,
953 &tm->tm_hour, &tm->tm_min,
956 dt2time(time * SECS_PER_DAY, &tm->tm_hour,
957 &tm->tm_min, &tm->tm_sec, fsec);
963 /* previous field was "t" for ISO time */
964 dterr = DecodeNumberField(strlen(field[i]), field[i],
965 (fmask | DTK_DATE_M),
970 if (tmask != DTK_TIME_M)
971 return DTERR_BAD_FORMAT;
975 return DTERR_BAD_FORMAT;
987 flen = strlen(field[i]);
988 cp = strchr(field[i], '.');
990 /* Embedded decimal and no date yet? */
991 if (cp != NULL && !(fmask & DTK_DATE_M))
993 dterr = DecodeDate(field[i], fmask, &tmask, tm);
997 /* embedded decimal and several digits before? */
998 else if (cp != NULL && flen - strlen(cp) > 2)
1001 * Interpret as a concatenated date or time Set the
1002 * type field to allow decoding other fields later.
1003 * Example: 20011223 or 040506
1005 dterr = DecodeNumberField(flen, field[i], fmask,
1013 dterr = DecodeNumberField(flen, field[i], fmask,
1019 /* otherwise it is a single date/time field... */
1022 dterr = DecodeNumber(flen, field[i],
1023 haveTextMonth, fmask,
1034 type = DecodeSpecial(i, field[i], &val);
1035 if (type == IGNORE_DTF)
1038 tmask = DTK_M(type);
1046 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1047 errmsg("date/time value \"current\" is no longer supported")));
1049 return DTERR_BAD_FORMAT;
1053 tmask = (DTK_DATE_M | DTK_TIME_M | DTK_M(TZ));
1055 GetCurrentTimeUsec(tm, fsec, tzp);
1061 GetCurrentDateTime(tm);
1062 j2date(date2j(tm->tm_year, tm->tm_mon, tm->tm_mday) - 1,
1063 &tm->tm_year, &tm->tm_mon, &tm->tm_mday);
1072 GetCurrentDateTime(tm);
1081 GetCurrentDateTime(tm);
1082 j2date(date2j(tm->tm_year, tm->tm_mon, tm->tm_mday) + 1,
1083 &tm->tm_year, &tm->tm_mon, &tm->tm_mday);
1090 tmask = (DTK_TIME_M | DTK_M(TZ));
1108 * already have a (numeric) month? then see if we can
1111 if ((fmask & DTK_M(MONTH)) && !haveTextMonth &&
1112 !(fmask & DTK_M(DAY)) && tm->tm_mon >= 1 &&
1115 tm->tm_mday = tm->tm_mon;
1118 haveTextMonth = TRUE;
1125 * daylight savings time modifier (solves "MET DST"
1128 tmask |= DTK_M(DTZ);
1131 return DTERR_BAD_FORMAT;
1132 *tzp += val * MINS_PER_HOUR;
1138 * set mask for TZ here _or_ check for DTZ later when
1139 * getting default timezone
1144 return DTERR_BAD_FORMAT;
1145 *tzp = val * MINS_PER_HOUR;
1151 return DTERR_BAD_FORMAT;
1152 *tzp = val * MINS_PER_HOUR;
1178 * This is a filler field "t" indicating that the next
1179 * field is time. Try to verify that this is sensible.
1183 /* No preceding date? Then quit... */
1184 if ((fmask & DTK_DATE_M) != DTK_DATE_M)
1185 return DTERR_BAD_FORMAT;
1188 * We will need one of the following fields:
1189 * DTK_NUMBER should be hhmmss.fff
1190 * DTK_TIME should be hh:mm:ss.fff
1191 * DTK_DATE should be hhmmss-zz
1194 (ftype[i + 1] != DTK_NUMBER &&
1195 ftype[i + 1] != DTK_TIME &&
1196 ftype[i + 1] != DTK_DATE))
1197 return DTERR_BAD_FORMAT;
1204 * Before giving up and declaring error, check to see
1205 * if it is an all-alpha timezone name.
1207 namedTz = pg_tzset(field[i]);
1209 return DTERR_BAD_FORMAT;
1210 /* we'll apply the zone setting below */
1215 return DTERR_BAD_FORMAT;
1220 return DTERR_BAD_FORMAT;
1224 return DTERR_BAD_FORMAT;
1228 if (fmask & DTK_M(YEAR))
1230 /* there is no year zero in AD/BC notation; i.e. "1 BC" == year 0 */
1233 if (tm->tm_year > 0)
1234 tm->tm_year = -(tm->tm_year - 1);
1237 (errcode(ERRCODE_INVALID_DATETIME_FORMAT),
1238 errmsg("inconsistent use of year %04d and \"BC\"",
1243 if (tm->tm_year < 70)
1244 tm->tm_year += 2000;
1245 else if (tm->tm_year < 100)
1246 tm->tm_year += 1900;
1250 /* now that we have correct year, decode DOY */
1251 if (fmask & DTK_M(DOY))
1253 j2date(date2j(tm->tm_year, 1, 1) + tm->tm_yday - 1,
1254 &tm->tm_year, &tm->tm_mon, &tm->tm_mday);
1257 /* check for valid month */
1258 if (fmask & DTK_M(MONTH))
1260 if (tm->tm_mon < 1 || tm->tm_mon > MONTHS_PER_YEAR)
1261 return DTERR_MD_FIELD_OVERFLOW;
1264 /* minimal check for valid day */
1265 if (fmask & DTK_M(DAY))
1267 if (tm->tm_mday < 1 || tm->tm_mday > 31)
1268 return DTERR_MD_FIELD_OVERFLOW;
1271 if (mer != HR24 && tm->tm_hour > 12)
1272 return DTERR_FIELD_OVERFLOW;
1273 if (mer == AM && tm->tm_hour == 12)
1275 else if (mer == PM && tm->tm_hour != 12)
1278 /* do additional checking for full date specs... */
1279 if (*dtype == DTK_DATE)
1281 if ((fmask & DTK_DATE_M) != DTK_DATE_M)
1283 if ((fmask & DTK_TIME_M) == DTK_TIME_M)
1285 return DTERR_BAD_FORMAT;
1289 * Check for valid day of month, now that we know for sure the month
1290 * and year. Note we don't use MD_FIELD_OVERFLOW here, since it seems
1291 * unlikely that "Feb 29" is a YMD-order error.
1293 if (tm->tm_mday > day_tab[isleap(tm->tm_year)][tm->tm_mon - 1])
1294 return DTERR_FIELD_OVERFLOW;
1297 * If we had a full timezone spec, compute the offset (we could not
1298 * do it before, because we need the date to resolve DST status).
1300 if (namedTz != NULL)
1302 /* daylight savings time modifier disallowed with full TZ */
1303 if (fmask & DTK_M(DTZMOD))
1304 return DTERR_BAD_FORMAT;
1306 *tzp = DetermineTimeZoneOffset(tm, namedTz);
1309 /* timezone not specified? then find local timezone if possible */
1310 if (tzp != NULL && !(fmask & DTK_M(TZ)))
1313 * daylight savings time modifier but no standard timezone? then
1316 if (fmask & DTK_M(DTZMOD))
1317 return DTERR_BAD_FORMAT;
1319 *tzp = DetermineTimeZoneOffset(tm, global_timezone);
1327 /* DetermineTimeZoneOffset()
1329 * Given a struct pg_tm in which tm_year, tm_mon, tm_mday, tm_hour, tm_min, and
1330 * tm_sec fields are set, attempt to determine the applicable time zone
1331 * (ie, regular or daylight-savings time) at that time. Set the struct pg_tm's
1332 * tm_isdst field accordingly, and return the actual timezone offset.
1334 * Note: it might seem that we should use mktime() for this, but bitter
1335 * experience teaches otherwise. This code is much faster than most versions
1336 * of mktime(), anyway.
1339 DetermineTimeZoneOffset(struct pg_tm * tm, pg_tz *tzp)
1349 long int before_gmtoff,
1355 if (tzp == global_timezone && HasCTZSet)
1357 tm->tm_isdst = 0; /* for lack of a better idea */
1362 * First, generate the pg_time_t value corresponding to the given
1363 * y/m/d/h/m/s taken as GMT time. If this overflows, punt and decide the
1364 * timezone is GMT. (We only need to worry about overflow on machines
1365 * where pg_time_t is 32 bits.)
1367 if (!IS_VALID_JULIAN(tm->tm_year, tm->tm_mon, tm->tm_mday))
1369 date = date2j(tm->tm_year, tm->tm_mon, tm->tm_mday) - UNIX_EPOCH_JDATE;
1371 day = ((pg_time_t) date) * SECS_PER_DAY;
1372 if (day / SECS_PER_DAY != date)
1374 sec = tm->tm_sec + (tm->tm_min + tm->tm_hour * MINS_PER_HOUR) * SECS_PER_MINUTE;
1376 /* since sec >= 0, overflow could only be from +day to -mytime */
1377 if (mytime < 0 && day > 0)
1381 * Find the DST time boundary just before or following the target time. We
1382 * assume that all zones have GMT offsets less than 24 hours, and that DST
1383 * boundaries can't be closer together than 48 hours, so backing up 24
1384 * hours and finding the "next" boundary will work.
1386 prevtime = mytime - SECS_PER_DAY;
1387 if (mytime < 0 && prevtime > 0)
1390 res = pg_next_dst_boundary(&prevtime,
1391 &before_gmtoff, &before_isdst,
1393 &after_gmtoff, &after_isdst,
1396 goto overflow; /* failure? */
1400 /* Non-DST zone, life is simple */
1401 tm->tm_isdst = before_isdst;
1402 return -(int) before_gmtoff;
1406 * Form the candidate pg_time_t values with local-time adjustment
1408 beforetime = mytime - before_gmtoff;
1409 if ((before_gmtoff > 0 &&
1410 mytime < 0 && beforetime > 0) ||
1411 (before_gmtoff <= 0 &&
1412 mytime > 0 && beforetime < 0))
1414 aftertime = mytime - after_gmtoff;
1415 if ((after_gmtoff > 0 &&
1416 mytime < 0 && aftertime > 0) ||
1417 (after_gmtoff <= 0 &&
1418 mytime > 0 && aftertime < 0))
1422 * If both before or both after the boundary time, we know what to do
1424 if (beforetime <= boundary && aftertime < boundary)
1426 tm->tm_isdst = before_isdst;
1427 return -(int) before_gmtoff;
1429 if (beforetime > boundary && aftertime >= boundary)
1431 tm->tm_isdst = after_isdst;
1432 return -(int) after_gmtoff;
1436 * It's an invalid or ambiguous time due to timezone transition. Prefer
1437 * the standard-time interpretation.
1439 if (after_isdst == 0)
1441 tm->tm_isdst = after_isdst;
1442 return -(int) after_gmtoff;
1444 tm->tm_isdst = before_isdst;
1445 return -(int) before_gmtoff;
1448 /* Given date is out of range, so assume UTC */
1455 * Interpret parsed string as time fields only.
1456 * Returns 0 if successful, DTERR code if bogus input detected.
1458 * Note that support for time zone is here for
1459 * SQL92 TIME WITH TIME ZONE, but it reveals
1460 * bogosity with SQL92 date/time standards, since
1461 * we must infer a time zone from current time.
1462 * - thomas 2000-03-10
1463 * Allow specifying date to get a better time zone,
1464 * if time zones are allowed. - thomas 2001-12-26
1467 DecodeTimeOnly(char **field, int *ftype, int nf,
1468 int *dtype, struct pg_tm * tm, fsec_t *fsec, int *tzp)
1473 int ptype = 0; /* "prefix type" for ISO h04mm05s06 format */
1477 int is2digits = FALSE;
1479 pg_tz *namedTz = NULL;
1486 /* don't know daylight savings time status apriori */
1492 for (i = 0; i < nf; i++)
1499 * Time zone not allowed? Then should not accept dates or time
1500 * zones no matter what else!
1503 return DTERR_BAD_FORMAT;
1505 /* Under limited circumstances, we will accept a date... */
1506 if (i == 0 && nf >= 2 &&
1507 (ftype[nf - 1] == DTK_DATE || ftype[1] == DTK_TIME))
1509 dterr = DecodeDate(field[i], fmask, &tmask, tm);
1513 /* otherwise, this is a time and/or time zone */
1516 if (isdigit((unsigned char) *field[i]))
1521 * Starts with a digit but we already have a time
1522 * field? Then we are in trouble with time already...
1524 if ((fmask & DTK_TIME_M) == DTK_TIME_M)
1525 return DTERR_BAD_FORMAT;
1528 * Should not get here and fail. Sanity check only...
1530 if ((cp = strchr(field[i], '-')) == NULL)
1531 return DTERR_BAD_FORMAT;
1533 /* Get the time zone from the end of the string */
1534 dterr = DecodeTimezone(cp, tzp);
1540 * Then read the rest of the field as a concatenated
1543 dterr = DecodeNumberField(strlen(field[i]), field[i],
1544 (fmask | DTK_DATE_M),
1555 namedTz = pg_tzset(field[i]);
1559 * We should return an error code instead of
1560 * ereport'ing directly, but then there is no
1561 * way to report the bad time zone name.
1564 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1565 errmsg("time zone \"%s\" not recognized",
1568 /* we'll apply the zone setting below */
1576 dterr = DecodeTime(field[i], (fmask | DTK_DATE_M),
1587 return DTERR_BAD_FORMAT;
1589 dterr = DecodeTimezone(field[i], &tz);
1600 * Was this an "ISO time" with embedded field labels? An
1601 * example is "h04m05s06" - thomas 2001-02-04
1608 /* Only accept a date under limited circumstances */
1616 return DTERR_BAD_FORMAT;
1622 val = strtol(field[i], &cp, 10);
1623 if (errno == ERANGE)
1624 return DTERR_FIELD_OVERFLOW;
1627 * only a few kinds are allowed to have an embedded
1638 return DTERR_BAD_FORMAT;
1641 else if (*cp != '\0')
1642 return DTERR_BAD_FORMAT;
1648 tmask = DTK_M(YEAR);
1654 * already have a month and hour? then assume
1657 if ((fmask & DTK_M(MONTH)) != 0 &&
1658 (fmask & DTK_M(HOUR)) != 0)
1661 tmask = DTK_M(MINUTE);
1666 tmask = DTK_M(MONTH);
1677 tmask = DTK_M(HOUR);
1682 tmask = DTK_M(MINUTE);
1687 tmask = DTK_M(SECOND);
1692 frac = strtod(cp, &cp);
1694 return DTERR_BAD_FORMAT;
1695 #ifdef HAVE_INT64_TIMESTAMP
1696 *fsec = rint(frac * 1000000);
1705 dterr = DecodeTimezone(field[i], tzp);
1712 * previous field was a label for "julian date"?
1715 j2date(val, &tm->tm_year, &tm->tm_mon, &tm->tm_mday);
1720 time = strtod(cp, &cp);
1722 return DTERR_BAD_FORMAT;
1724 tmask |= DTK_TIME_M;
1725 #ifdef HAVE_INT64_TIMESTAMP
1726 dt2time(time * USECS_PER_DAY,
1727 &tm->tm_hour, &tm->tm_min, &tm->tm_sec, fsec);
1729 dt2time(time * SECS_PER_DAY,
1730 &tm->tm_hour, &tm->tm_min, &tm->tm_sec, fsec);
1736 /* previous field was "t" for ISO time */
1737 dterr = DecodeNumberField(strlen(field[i]), field[i],
1738 (fmask | DTK_DATE_M),
1745 if (tmask != DTK_TIME_M)
1746 return DTERR_BAD_FORMAT;
1750 return DTERR_BAD_FORMAT;
1762 flen = strlen(field[i]);
1763 cp = strchr(field[i], '.');
1765 /* Embedded decimal? */
1769 * Under limited circumstances, we will accept a
1772 if (i == 0 && nf >= 2 && ftype[nf - 1] == DTK_DATE)
1774 dterr = DecodeDate(field[i], fmask, &tmask, tm);
1778 /* embedded decimal and several digits before? */
1779 else if (flen - strlen(cp) > 2)
1782 * Interpret as a concatenated date or time Set
1783 * the type field to allow decoding other fields
1784 * later. Example: 20011223 or 040506
1786 dterr = DecodeNumberField(flen, field[i],
1787 (fmask | DTK_DATE_M),
1795 return DTERR_BAD_FORMAT;
1799 dterr = DecodeNumberField(flen, field[i],
1800 (fmask | DTK_DATE_M),
1807 /* otherwise it is a single date/time field... */
1810 dterr = DecodeNumber(flen, field[i],
1812 (fmask | DTK_DATE_M),
1823 type = DecodeSpecial(i, field[i], &val);
1824 if (type == IGNORE_DTF)
1827 tmask = DTK_M(type);
1835 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1836 errmsg("date/time value \"current\" is no longer supported")));
1837 return DTERR_BAD_FORMAT;
1843 GetCurrentTimeUsec(tm, fsec, NULL);
1847 tmask = (DTK_TIME_M | DTK_M(TZ));
1856 return DTERR_BAD_FORMAT;
1864 * daylight savings time modifier (solves "MET DST"
1867 tmask |= DTK_M(DTZ);
1870 return DTERR_BAD_FORMAT;
1871 *tzp += val * MINS_PER_HOUR;
1877 * set mask for TZ here _or_ check for DTZ later when
1878 * getting default timezone
1883 return DTERR_BAD_FORMAT;
1884 *tzp = val * MINS_PER_HOUR;
1891 return DTERR_BAD_FORMAT;
1892 *tzp = val * MINS_PER_HOUR;
1912 * We will need one of the following fields:
1913 * DTK_NUMBER should be hhmmss.fff
1914 * DTK_TIME should be hh:mm:ss.fff
1915 * DTK_DATE should be hhmmss-zz
1918 (ftype[i + 1] != DTK_NUMBER &&
1919 ftype[i + 1] != DTK_TIME &&
1920 ftype[i + 1] != DTK_DATE))
1921 return DTERR_BAD_FORMAT;
1928 * Before giving up and declaring error, check to see
1929 * if it is an all-alpha timezone name.
1931 namedTz = pg_tzset(field[i]);
1933 return DTERR_BAD_FORMAT;
1934 /* we'll apply the zone setting below */
1939 return DTERR_BAD_FORMAT;
1944 return DTERR_BAD_FORMAT;
1948 return DTERR_BAD_FORMAT;
1952 if (mer != HR24 && tm->tm_hour > 12)
1953 return DTERR_FIELD_OVERFLOW;
1954 if (mer == AM && tm->tm_hour == 12)
1956 else if (mer == PM && tm->tm_hour != 12)
1959 if (tm->tm_hour < 0 || tm->tm_min < 0 || tm->tm_min > 59 ||
1960 tm->tm_sec < 0 || tm->tm_sec > 60 || tm->tm_hour > 24 ||
1961 /* test for > 24:00:00 */
1962 #ifdef HAVE_INT64_TIMESTAMP
1963 (tm->tm_hour == 24 && (tm->tm_min > 0 || tm->tm_sec > 0 ||
1964 *fsec > INT64CONST(0))) ||
1965 *fsec < INT64CONST(0) || *fsec >= USECS_PER_SEC
1967 (tm->tm_hour == 24 && (tm->tm_min > 0 || tm->tm_sec > 0 ||
1969 *fsec < 0 || *fsec >= 1
1972 return DTERR_FIELD_OVERFLOW;
1974 if ((fmask & DTK_TIME_M) != DTK_TIME_M)
1975 return DTERR_BAD_FORMAT;
1978 * If we had a full timezone spec, compute the offset (we could not
1979 * do it before, because we may need the date to resolve DST status).
1981 if (namedTz != NULL)
1985 /* daylight savings time modifier disallowed with full TZ */
1986 if (fmask & DTK_M(DTZMOD))
1987 return DTERR_BAD_FORMAT;
1989 /* if non-DST zone, we do not need to know the date */
1990 if (pg_get_timezone_offset(namedTz, &gmtoff))
1992 *tzp = -(int) gmtoff;
1996 /* a date has to be specified */
1997 if ((fmask & DTK_DATE_M) != DTK_DATE_M)
1998 return DTERR_BAD_FORMAT;
1999 *tzp = DetermineTimeZoneOffset(tm, namedTz);
2003 /* timezone not specified? then find local timezone if possible */
2004 if (tzp != NULL && !(fmask & DTK_M(TZ)))
2010 * daylight savings time modifier but no standard timezone? then error
2012 if (fmask & DTK_M(DTZMOD))
2013 return DTERR_BAD_FORMAT;
2015 if ((fmask & DTK_DATE_M) == 0)
2016 GetCurrentDateTime(tmp);
2019 tmp->tm_year = tm->tm_year;
2020 tmp->tm_mon = tm->tm_mon;
2021 tmp->tm_mday = tm->tm_mday;
2023 tmp->tm_hour = tm->tm_hour;
2024 tmp->tm_min = tm->tm_min;
2025 tmp->tm_sec = tm->tm_sec;
2026 *tzp = DetermineTimeZoneOffset(tmp, global_timezone);
2027 tm->tm_isdst = tmp->tm_isdst;
2034 * Decode date string which includes delimiters.
2035 * Return 0 if okay, a DTERR code if not.
2037 * Insist on a complete set of fields.
2040 DecodeDate(char *str, int fmask, int *tmask, struct pg_tm * tm)
2047 bool haveTextMonth = FALSE;
2049 int is2digits = FALSE;
2053 char *field[MAXDATEFIELDS];
2055 /* parse this string... */
2056 while (*str != '\0' && nf < MAXDATEFIELDS)
2058 /* skip field separators */
2059 while (!isalnum((unsigned char) *str))
2063 if (isdigit((unsigned char) *str))
2065 while (isdigit((unsigned char) *str))
2068 else if (isalpha((unsigned char) *str))
2070 while (isalpha((unsigned char) *str))
2074 /* Just get rid of any non-digit, non-alpha characters... */
2081 /* don't allow too many fields */
2083 return DTERR_BAD_FORMAT;
2088 /* look first for text fields, since that will be unambiguous month */
2089 for (i = 0; i < nf; i++)
2091 if (isalpha((unsigned char) *field[i]))
2093 type = DecodeSpecial(i, field[i], &val);
2094 if (type == IGNORE_DTF)
2097 dmask = DTK_M(type);
2102 haveTextMonth = TRUE;
2110 return DTERR_BAD_FORMAT;
2113 return DTERR_BAD_FORMAT;
2118 /* mark this field as being completed */
2123 /* now pick up remaining numeric fields */
2124 for (i = 0; i < nf; i++)
2126 if (field[i] == NULL)
2129 if ((len = strlen(field[i])) <= 0)
2130 return DTERR_BAD_FORMAT;
2132 dterr = DecodeNumber(len, field[i], haveTextMonth, fmask,
2139 return DTERR_BAD_FORMAT;
2145 if ((fmask & ~(DTK_M(DOY) | DTK_M(TZ))) != DTK_DATE_M)
2146 return DTERR_BAD_FORMAT;
2148 /* there is no year zero in AD/BC notation; i.e. "1 BC" == year 0 */
2151 if (tm->tm_year > 0)
2152 tm->tm_year = -(tm->tm_year - 1);
2155 (errcode(ERRCODE_INVALID_DATETIME_FORMAT),
2156 errmsg("inconsistent use of year %04d and \"BC\"",
2161 if (tm->tm_year < 70)
2162 tm->tm_year += 2000;
2163 else if (tm->tm_year < 100)
2164 tm->tm_year += 1900;
2167 /* now that we have correct year, decode DOY */
2168 if (fmask & DTK_M(DOY))
2170 j2date(date2j(tm->tm_year, 1, 1) + tm->tm_yday - 1,
2171 &tm->tm_year, &tm->tm_mon, &tm->tm_mday);
2174 /* check for valid month */
2175 if (tm->tm_mon < 1 || tm->tm_mon > MONTHS_PER_YEAR)
2176 return DTERR_MD_FIELD_OVERFLOW;
2178 /* check for valid day */
2179 if (tm->tm_mday < 1 || tm->tm_mday > 31)
2180 return DTERR_MD_FIELD_OVERFLOW;
2182 /* We don't want to hint about DateStyle for Feb 29 */
2183 if (tm->tm_mday > day_tab[isleap(tm->tm_year)][tm->tm_mon - 1])
2184 return DTERR_FIELD_OVERFLOW;
2191 * Decode time string which includes delimiters.
2192 * Return 0 if okay, a DTERR code if not.
2194 * Only check the lower limit on hours, since this same code
2195 * can be used to represent time spans.
2198 DecodeTime(char *str, int fmask, int *tmask, struct pg_tm * tm, fsec_t *fsec)
2202 *tmask = DTK_TIME_M;
2205 tm->tm_hour = strtol(str, &cp, 10);
2206 if (errno == ERANGE)
2207 return DTERR_FIELD_OVERFLOW;
2209 return DTERR_BAD_FORMAT;
2212 tm->tm_min = strtol(str, &cp, 10);
2213 if (errno == ERANGE)
2214 return DTERR_FIELD_OVERFLOW;
2220 else if (*cp != ':')
2221 return DTERR_BAD_FORMAT;
2226 tm->tm_sec = strtol(str, &cp, 10);
2227 if (errno == ERANGE)
2228 return DTERR_FIELD_OVERFLOW;
2231 else if (*cp == '.')
2236 frac = strtod(str, &cp);
2238 return DTERR_BAD_FORMAT;
2239 #ifdef HAVE_INT64_TIMESTAMP
2240 *fsec = rint(frac * 1000000);
2246 return DTERR_BAD_FORMAT;
2249 /* do a sanity check */
2250 #ifdef HAVE_INT64_TIMESTAMP
2251 if (tm->tm_hour < 0 || tm->tm_min < 0 || tm->tm_min > 59 ||
2252 tm->tm_sec < 0 || tm->tm_sec > 60 || *fsec < INT64CONST(0) ||
2253 *fsec >= USECS_PER_SEC)
2254 return DTERR_FIELD_OVERFLOW;
2256 if (tm->tm_hour < 0 || tm->tm_min < 0 || tm->tm_min > 59 ||
2257 tm->tm_sec < 0 || tm->tm_sec > 60 || *fsec < 0 || *fsec >= 1)
2258 return DTERR_FIELD_OVERFLOW;
2266 * Interpret plain numeric field as a date value in context.
2267 * Return 0 if okay, a DTERR code if not.
2270 DecodeNumber(int flen, char *str, bool haveTextMonth, int fmask,
2271 int *tmask, struct pg_tm * tm, fsec_t *fsec, int *is2digits)
2280 val = strtol(str, &cp, 10);
2281 if (errno == ERANGE)
2282 return DTERR_FIELD_OVERFLOW;
2284 return DTERR_BAD_FORMAT;
2291 * More than two digits before decimal point? Then could be a date or
2292 * a run-together time: 2001.360 20011225 040506.789
2296 dterr = DecodeNumberField(flen, str,
2297 (fmask | DTK_DATE_M),
2305 frac = strtod(cp, &cp);
2307 return DTERR_BAD_FORMAT;
2308 #ifdef HAVE_INT64_TIMESTAMP
2309 *fsec = rint(frac * 1000000);
2314 else if (*cp != '\0')
2315 return DTERR_BAD_FORMAT;
2317 /* Special case for day of year */
2318 if (flen == 3 && (fmask & DTK_DATE_M) == DTK_M(YEAR) && val >= 1 &&
2321 *tmask = (DTK_M(DOY) | DTK_M(MONTH) | DTK_M(DAY));
2323 /* tm_mon and tm_mday can't actually be set yet ... */
2327 /* Switch based on what we have so far */
2328 switch (fmask & DTK_DATE_M)
2333 * Nothing so far; make a decision about what we think the input
2334 * is. There used to be lots of heuristics here, but the
2335 * consensus now is to be paranoid. It *must* be either
2336 * YYYY-MM-DD (with a more-than-two-digit year field), or the
2337 * field order defined by DateOrder.
2339 if (flen >= 3 || DateOrder == DATEORDER_YMD)
2341 *tmask = DTK_M(YEAR);
2344 else if (DateOrder == DATEORDER_DMY)
2346 *tmask = DTK_M(DAY);
2351 *tmask = DTK_M(MONTH);
2357 /* Must be at second field of YY-MM-DD */
2358 *tmask = DTK_M(MONTH);
2362 case (DTK_M(MONTH)):
2366 * We are at the first numeric field of a date that included a
2367 * textual month name. We want to support the variants
2368 * MON-DD-YYYY, DD-MON-YYYY, and YYYY-MON-DD as unambiguous
2369 * inputs. We will also accept MON-DD-YY or DD-MON-YY in
2370 * either DMY or MDY modes, as well as YY-MON-DD in YMD mode.
2372 if (flen >= 3 || DateOrder == DATEORDER_YMD)
2374 *tmask = DTK_M(YEAR);
2379 *tmask = DTK_M(DAY);
2385 /* Must be at second field of MM-DD-YY */
2386 *tmask = DTK_M(DAY);
2391 case (DTK_M(YEAR) | DTK_M(MONTH)):
2394 /* Need to accept DD-MON-YYYY even in YMD mode */
2395 if (flen >= 3 && *is2digits)
2397 /* Guess that first numeric field is day was wrong */
2398 *tmask = DTK_M(DAY); /* YEAR is already set */
2399 tm->tm_mday = tm->tm_year;
2405 *tmask = DTK_M(DAY);
2411 /* Must be at third field of YY-MM-DD */
2412 *tmask = DTK_M(DAY);
2418 /* Must be at second field of DD-MM-YY */
2419 *tmask = DTK_M(MONTH);
2423 case (DTK_M(MONTH) | DTK_M(DAY)):
2424 /* Must be at third field of DD-MM-YY or MM-DD-YY */
2425 *tmask = DTK_M(YEAR);
2429 case (DTK_M(YEAR) | DTK_M(MONTH) | DTK_M(DAY)):
2430 /* we have all the date, so it must be a time field */
2431 dterr = DecodeNumberField(flen, str, fmask,
2439 /* Anything else is bogus input */
2440 return DTERR_BAD_FORMAT;
2444 * When processing a year field, mark it for adjustment if it's only one
2447 if (*tmask == DTK_M(YEAR))
2448 *is2digits = (flen <= 2);
2454 /* DecodeNumberField()
2455 * Interpret numeric string as a concatenated date or time field.
2456 * Return a DTK token (>= 0) if successful, a DTERR code (< 0) if not.
2458 * Use the context of previously decoded fields to help with
2459 * the interpretation.
2462 DecodeNumberField(int len, char *str, int fmask,
2463 int *tmask, struct pg_tm * tm, fsec_t *fsec, int *is2digits)
2468 * Have a decimal point? Then this is a date or something with a seconds
2471 if ((cp = strchr(str, '.')) != NULL)
2475 frac = strtod(cp, NULL);
2476 #ifdef HAVE_INT64_TIMESTAMP
2477 *fsec = rint(frac * 1000000);
2484 /* No decimal point and no complete date yet? */
2485 else if ((fmask & DTK_DATE_M) != DTK_DATE_M)
2490 *tmask = DTK_DATE_M;
2492 tm->tm_mday = atoi(str + 6);
2494 tm->tm_mon = atoi(str + 4);
2496 tm->tm_year = atoi(str + 0);
2503 *tmask = DTK_DATE_M;
2504 tm->tm_mday = atoi(str + 4);
2506 tm->tm_mon = atoi(str + 2);
2508 tm->tm_year = atoi(str + 0);
2515 /* not all time fields are specified? */
2516 if ((fmask & DTK_TIME_M) != DTK_TIME_M)
2521 *tmask = DTK_TIME_M;
2522 tm->tm_sec = atoi(str + 4);
2524 tm->tm_min = atoi(str + 2);
2526 tm->tm_hour = atoi(str + 0);
2533 *tmask = DTK_TIME_M;
2535 tm->tm_min = atoi(str + 2);
2537 tm->tm_hour = atoi(str + 0);
2543 return DTERR_BAD_FORMAT;
2548 * Interpret string as a numeric timezone.
2550 * Return 0 if okay (and set *tzp), a DTERR code if not okay.
2552 * NB: this must *not* ereport on failure; see commands/variable.c.
2554 * Note: we allow timezone offsets up to 13:59. There are places that
2555 * use +1300 summer time.
2558 DecodeTimezone(char *str, int *tzp)
2566 /* leading character must be "+" or "-" */
2567 if (*str != '+' && *str != '-')
2568 return DTERR_BAD_FORMAT;
2571 hr = strtol(str + 1, &cp, 10);
2572 if (errno == ERANGE)
2573 return DTERR_TZDISP_OVERFLOW;
2575 /* explicit delimiter? */
2579 min = strtol(cp + 1, &cp, 10);
2580 if (errno == ERANGE)
2581 return DTERR_TZDISP_OVERFLOW;
2585 sec = strtol(cp + 1, &cp, 10);
2586 if (errno == ERANGE)
2587 return DTERR_TZDISP_OVERFLOW;
2590 /* otherwise, might have run things together... */
2591 else if (*cp == '\0' && strlen(str) > 3)
2595 /* we could, but don't, support a run-together hhmmss format */
2600 if (hr < 0 || hr > 14)
2601 return DTERR_TZDISP_OVERFLOW;
2602 if (min < 0 || min >= 60)
2603 return DTERR_TZDISP_OVERFLOW;
2604 if (sec < 0 || sec >= 60)
2605 return DTERR_TZDISP_OVERFLOW;
2607 tz = (hr * MINS_PER_HOUR + min) * SECS_PER_MINUTE + sec;
2614 return DTERR_BAD_FORMAT;
2620 * Decode text string using lookup table.
2622 * Implement a cache lookup since it is likely that dates
2623 * will be related in format.
2625 * NB: this must *not* ereport on failure;
2626 * see commands/variable.c.
2629 DecodeSpecial(int field, char *lowtoken, int *val)
2634 tp = datecache[field];
2635 if (tp == NULL || strncmp(lowtoken, tp->token, TOKMAXLEN) != 0)
2637 tp = datebsearch(lowtoken, timezonetktbl, sztimezonetktbl);
2639 tp = datebsearch(lowtoken, datetktbl, szdatetktbl);
2643 type = UNKNOWN_FIELD;
2648 datecache[field] = tp;
2669 * Interpret previously parsed fields for general time interval.
2670 * Returns 0 if successful, DTERR code if bogus input detected.
2672 * Allow "date" field DTK_DATE since this could be just
2673 * an unsigned floating point number. - thomas 1997-11-16
2675 * Allow ISO-style time span, with implicit units on number of days
2676 * preceding an hh:mm:ss field. - thomas 1998-04-30
2679 DecodeInterval(char **field, int *ftype, int nf, int *dtype, struct pg_tm * tm, fsec_t *fsec)
2681 int is_before = FALSE;
2702 /* read through list backwards to pick up units before values */
2703 for (i = nf - 1; i >= 0; i--)
2708 dterr = DecodeTime(field[i], fmask, &tmask, tm, fsec);
2717 * Timezone is a token with a leading sign character and
2718 * otherwise the same as a non-signed time field
2720 Assert(*field[i] == '-' || *field[i] == '+');
2723 * A single signed number ends up here, but will be rejected
2724 * by DecodeTime(). So, work this out to drop through to
2725 * DTK_NUMBER, which *can* tolerate this.
2728 while (*cp != '\0' && *cp != ':' && *cp != '.')
2731 DecodeTime(field[i] + 1, fmask, &tmask, tm, fsec) == 0)
2733 if (*field[i] == '-')
2735 /* flip the sign on all fields */
2736 tm->tm_hour = -tm->tm_hour;
2737 tm->tm_min = -tm->tm_min;
2738 tm->tm_sec = -tm->tm_sec;
2743 * Set the next type to be a day, if units are not
2744 * specified. This handles the case of '1 +02:03' since we
2745 * are reading right to left.
2751 else if (type == IGNORE_DTF)
2756 * Got a decimal point? Then assume some sort of
2757 * seconds specification
2761 else if (*cp == '\0')
2764 * Only a signed integer? Then must assume a
2765 * timezone-like usage
2775 val = strtol(field[i], &cp, 10);
2776 if (errno == ERANGE)
2777 return DTERR_FIELD_OVERFLOW;
2779 if (type == IGNORE_DTF)
2784 fval = strtod(cp, &cp);
2786 return DTERR_BAD_FORMAT;
2788 if (*field[i] == '-')
2791 else if (*cp == '\0')
2794 return DTERR_BAD_FORMAT;
2796 tmask = 0; /* DTK_M(type); */
2801 #ifdef HAVE_INT64_TIMESTAMP
2802 *fsec += val + fval;
2804 *fsec += (val + fval) * 1e-6;
2809 #ifdef HAVE_INT64_TIMESTAMP
2810 *fsec += (val + fval) * 1000;
2812 *fsec += (val + fval) * 1e-3;
2818 #ifdef HAVE_INT64_TIMESTAMP
2819 *fsec += fval * 1000000;
2823 tmask = DTK_M(SECOND);
2832 fval *= SECS_PER_MINUTE;
2835 #ifdef HAVE_INT64_TIMESTAMP
2836 *fsec += (fval - sec) * 1000000;
2838 *fsec += fval - sec;
2841 tmask = DTK_M(MINUTE);
2850 fval *= SECS_PER_HOUR;
2853 #ifdef HAVE_INT64_TIMESTAMP
2854 *fsec += (fval - sec) * 1000000;
2856 *fsec += fval - sec;
2859 tmask = DTK_M(HOUR);
2868 fval *= SECS_PER_DAY;
2871 #ifdef HAVE_INT64_TIMESTAMP
2872 *fsec += (fval - sec) * 1000000;
2874 *fsec += fval - sec;
2877 tmask = (fmask & DTK_M(DAY)) ? 0 : DTK_M(DAY);
2881 tm->tm_mday += val * 7;
2887 extra_days = (int32) fval;
2888 tm->tm_mday += extra_days;
2894 fval *= SECS_PER_DAY;
2897 #ifdef HAVE_INT64_TIMESTAMP
2898 *fsec += (fval - sec) * 1000000;
2900 *fsec += fval - sec;
2904 tmask = (fmask & DTK_M(DAY)) ? 0 : DTK_M(DAY);
2913 fval *= DAYS_PER_MONTH;
2921 fval *= SECS_PER_DAY;
2924 #ifdef HAVE_INT64_TIMESTAMP
2925 *fsec += (fval - sec) * 1000000;
2927 *fsec += fval - sec;
2931 tmask = DTK_M(MONTH);
2937 tm->tm_mon += fval * MONTHS_PER_YEAR;
2938 tmask = (fmask & DTK_M(YEAR)) ? 0 : DTK_M(YEAR);
2942 tm->tm_year += val * 10;
2944 tm->tm_mon += fval * MONTHS_PER_YEAR * 10;
2945 tmask = (fmask & DTK_M(YEAR)) ? 0 : DTK_M(YEAR);
2949 tm->tm_year += val * 100;
2951 tm->tm_mon += fval * MONTHS_PER_YEAR * 100;
2952 tmask = (fmask & DTK_M(YEAR)) ? 0 : DTK_M(YEAR);
2955 case DTK_MILLENNIUM:
2956 tm->tm_year += val * 1000;
2958 tm->tm_mon += fval * MONTHS_PER_YEAR * 1000;
2959 tmask = (fmask & DTK_M(YEAR)) ? 0 : DTK_M(YEAR);
2963 return DTERR_BAD_FORMAT;
2969 type = DecodeUnits(i, field[i], &val);
2970 if (type == IGNORE_DTF)
2973 tmask = 0; /* DTK_M(type); */
2986 tmask = (DTK_DATE_M || DTK_TIME_M);
2991 return DTERR_BAD_FORMAT;
2996 return DTERR_BAD_FORMAT;
3000 return DTERR_BAD_FORMAT;
3008 #ifdef HAVE_INT64_TIMESTAMP
3009 sec = *fsec / USECS_PER_SEC;
3010 *fsec -= sec * USECS_PER_SEC;
3012 TMODULO(*fsec, sec, 1.0);
3020 tm->tm_sec = -tm->tm_sec;
3021 tm->tm_min = -tm->tm_min;
3022 tm->tm_hour = -tm->tm_hour;
3023 tm->tm_mday = -tm->tm_mday;
3024 tm->tm_mon = -tm->tm_mon;
3025 tm->tm_year = -tm->tm_year;
3028 /* ensure that at least one time field has been found */
3030 return DTERR_BAD_FORMAT;
3037 * Decode text string using lookup table.
3038 * This routine supports time interval decoding
3039 * (hence, it need not recognize timezone names).
3042 DecodeUnits(int field, char *lowtoken, int *val)
3047 tp = deltacache[field];
3048 if (tp == NULL || strncmp(lowtoken, tp->token, TOKMAXLEN) != 0)
3050 tp = datebsearch(lowtoken, deltatktbl, szdeltatktbl);
3054 type = UNKNOWN_FIELD;
3059 deltacache[field] = tp;
3061 if (type == TZ || type == DTZ)
3068 } /* DecodeUnits() */
3071 * Report an error detected by one of the datetime input processing routines.
3073 * dterr is the error code, str is the original input string, datatype is
3074 * the name of the datatype we were trying to accept.
3076 * Note: it might seem useless to distinguish DTERR_INTERVAL_OVERFLOW and
3077 * DTERR_TZDISP_OVERFLOW from DTERR_FIELD_OVERFLOW, but SQL99 mandates three
3078 * separate SQLSTATE codes, so ...
3081 DateTimeParseError(int dterr, const char *str, const char *datatype)
3085 case DTERR_FIELD_OVERFLOW:
3087 (errcode(ERRCODE_DATETIME_FIELD_OVERFLOW),
3088 errmsg("date/time field value out of range: \"%s\"",
3091 case DTERR_MD_FIELD_OVERFLOW:
3092 /* <nanny>same as above, but add hint about DateStyle</nanny> */
3094 (errcode(ERRCODE_DATETIME_FIELD_OVERFLOW),
3095 errmsg("date/time field value out of range: \"%s\"",
3097 errhint("Perhaps you need a different \"datestyle\" setting.")));
3099 case DTERR_INTERVAL_OVERFLOW:
3101 (errcode(ERRCODE_INTERVAL_FIELD_OVERFLOW),
3102 errmsg("interval field value out of range: \"%s\"",
3105 case DTERR_TZDISP_OVERFLOW:
3107 (errcode(ERRCODE_INVALID_TIME_ZONE_DISPLACEMENT_VALUE),
3108 errmsg("time zone displacement out of range: \"%s\"",
3111 case DTERR_BAD_FORMAT:
3114 (errcode(ERRCODE_INVALID_DATETIME_FORMAT),
3115 errmsg("invalid input syntax for type %s: \"%s\"",
3122 * Binary search -- from Knuth (6.2.1) Algorithm B. Special case like this
3123 * is WAY faster than the generic bsearch().
3125 static const datetkn *
3126 datebsearch(const char *key, const datetkn *base, int nel)
3128 const datetkn *last = base + nel - 1,
3132 while (last >= base)
3134 position = base + ((last - base) >> 1);
3135 result = key[0] - position->token[0];
3138 result = strncmp(key, position->token, TOKMAXLEN);
3143 last = position - 1;
3145 base = position + 1;
3151 * Append representation of a numeric timezone offset to str.
3154 EncodeTimezone(char *str, int tz)
3161 min = sec / SECS_PER_MINUTE;
3162 sec -= min * SECS_PER_MINUTE;
3163 hour = min / MINS_PER_HOUR;
3164 min -= hour * MINS_PER_HOUR;
3167 /* TZ is negated compared to sign we wish to display ... */
3168 *str++ = (tz <= 0 ? '+' : '-');
3171 sprintf(str, "%02d:%02d:%02d", hour, min, sec);
3173 sprintf(str, "%02d:%02d", hour, min);
3175 sprintf(str, "%02d", hour);
3179 * Encode date as local time.
3182 EncodeDateOnly(struct pg_tm * tm, int style, char *str)
3184 if (tm->tm_mon < 1 || tm->tm_mon > MONTHS_PER_YEAR)
3190 /* compatible with ISO date formats */
3191 if (tm->tm_year > 0)
3192 sprintf(str, "%04d-%02d-%02d",
3193 tm->tm_year, tm->tm_mon, tm->tm_mday);
3195 sprintf(str, "%04d-%02d-%02d %s",
3196 -(tm->tm_year - 1), tm->tm_mon, tm->tm_mday, "BC");
3200 /* compatible with Oracle/Ingres date formats */
3201 if (DateOrder == DATEORDER_DMY)
3202 sprintf(str, "%02d/%02d", tm->tm_mday, tm->tm_mon);
3204 sprintf(str, "%02d/%02d", tm->tm_mon, tm->tm_mday);
3205 if (tm->tm_year > 0)
3206 sprintf(str + 5, "/%04d", tm->tm_year);
3208 sprintf(str + 5, "/%04d %s", -(tm->tm_year - 1), "BC");
3211 case USE_GERMAN_DATES:
3212 /* German-style date format */
3213 sprintf(str, "%02d.%02d", tm->tm_mday, tm->tm_mon);
3214 if (tm->tm_year > 0)
3215 sprintf(str + 5, ".%04d", tm->tm_year);
3217 sprintf(str + 5, ".%04d %s", -(tm->tm_year - 1), "BC");
3220 case USE_POSTGRES_DATES:
3222 /* traditional date-only style for Postgres */
3223 if (DateOrder == DATEORDER_DMY)
3224 sprintf(str, "%02d-%02d", tm->tm_mday, tm->tm_mon);
3226 sprintf(str, "%02d-%02d", tm->tm_mon, tm->tm_mday);
3227 if (tm->tm_year > 0)
3228 sprintf(str + 5, "-%04d", tm->tm_year);
3230 sprintf(str + 5, "-%04d %s", -(tm->tm_year - 1), "BC");
3235 } /* EncodeDateOnly() */
3239 * Encode time fields only.
3242 EncodeTimeOnly(struct pg_tm * tm, fsec_t fsec, int *tzp, int style, char *str)
3244 if (tm->tm_hour < 0 || tm->tm_hour > HOURS_PER_DAY)
3247 sprintf(str, "%02d:%02d", tm->tm_hour, tm->tm_min);
3250 * Print fractional seconds if any. The fractional field widths here
3251 * should be equal to the larger of MAX_TIME_PRECISION and
3252 * MAX_TIMESTAMP_PRECISION.
3256 #ifdef HAVE_INT64_TIMESTAMP
3257 sprintf(str + strlen(str), ":%02d.%06d", tm->tm_sec, fsec);
3259 sprintf(str + strlen(str), ":%013.10f", tm->tm_sec + fsec);
3261 TrimTrailingZeros(str);
3264 sprintf(str + strlen(str), ":%02d", tm->tm_sec);
3267 EncodeTimezone(str, *tzp);
3270 } /* EncodeTimeOnly() */
3274 * Encode date and time interpreted as local time.
3275 * Support several date styles:
3276 * Postgres - day mon hh:mm:ss yyyy tz
3277 * SQL - mm/dd/yyyy hh:mm:ss.ss tz
3278 * ISO - yyyy-mm-dd hh:mm:ss+/-tz
3279 * German - dd.mm.yyyy hh:mm:ss tz
3280 * Variants (affects order of month and day for Postgres and SQL styles):
3282 * European - dd/mm/yyyy
3285 EncodeDateTime(struct pg_tm * tm, fsec_t fsec, int *tzp, char **tzn, int style, char *str)
3290 * Why are we checking only the month field? Change this to an assert...
3291 * if (tm->tm_mon < 1 || tm->tm_mon > MONTHS_PER_YEAR) return -1;
3293 Assert(tm->tm_mon >= 1 && tm->tm_mon <= MONTHS_PER_YEAR);
3298 /* Compatible with ISO-8601 date formats */
3300 sprintf(str, "%04d-%02d-%02d %02d:%02d",
3301 (tm->tm_year > 0) ? tm->tm_year : -(tm->tm_year - 1),
3302 tm->tm_mon, tm->tm_mday, tm->tm_hour, tm->tm_min);
3305 * Print fractional seconds if any. The field widths here should
3306 * be at least equal to MAX_TIMESTAMP_PRECISION.
3308 * In float mode, don't print fractional seconds before 1 AD,
3309 * since it's unlikely there's any precision left ...
3311 #ifdef HAVE_INT64_TIMESTAMP
3314 sprintf(str + strlen(str), ":%02d.%06d", tm->tm_sec, fsec);
3315 TrimTrailingZeros(str);
3318 if (fsec != 0 && tm->tm_year > 0)
3320 sprintf(str + strlen(str), ":%09.6f", tm->tm_sec + fsec);
3321 TrimTrailingZeros(str);
3325 sprintf(str + strlen(str), ":%02d", tm->tm_sec);
3328 * tzp == NULL indicates that we don't want *any* time zone info
3329 * in the output string. *tzn != NULL indicates that we have alpha
3330 * time zone info available. tm_isdst != -1 indicates that we have
3331 * a valid time zone translation.
3333 if (tzp != NULL && tm->tm_isdst >= 0)
3334 EncodeTimezone(str, *tzp);
3336 if (tm->tm_year <= 0)
3337 sprintf(str + strlen(str), " BC");
3341 /* Compatible with Oracle/Ingres date formats */
3343 if (DateOrder == DATEORDER_DMY)
3344 sprintf(str, "%02d/%02d", tm->tm_mday, tm->tm_mon);
3346 sprintf(str, "%02d/%02d", tm->tm_mon, tm->tm_mday);
3348 sprintf(str + 5, "/%04d %02d:%02d",
3349 (tm->tm_year > 0) ? tm->tm_year : -(tm->tm_year - 1),
3350 tm->tm_hour, tm->tm_min);
3353 * Print fractional seconds if any. The field widths here should
3354 * be at least equal to MAX_TIMESTAMP_PRECISION.
3356 * In float mode, don't print fractional seconds before 1 AD,
3357 * since it's unlikely there's any precision left ...
3359 #ifdef HAVE_INT64_TIMESTAMP
3362 sprintf(str + strlen(str), ":%02d.%06d", tm->tm_sec, fsec);
3363 TrimTrailingZeros(str);
3366 if (fsec != 0 && tm->tm_year > 0)
3368 sprintf(str + strlen(str), ":%09.6f", tm->tm_sec + fsec);
3369 TrimTrailingZeros(str);
3373 sprintf(str + strlen(str), ":%02d", tm->tm_sec);
3375 if (tzp != NULL && tm->tm_isdst >= 0)
3378 sprintf(str + strlen(str), " %.*s", MAXTZLEN, *tzn);
3380 EncodeTimezone(str, *tzp);
3383 if (tm->tm_year <= 0)
3384 sprintf(str + strlen(str), " BC");
3387 case USE_GERMAN_DATES:
3388 /* German variant on European style */
3390 sprintf(str, "%02d.%02d", tm->tm_mday, tm->tm_mon);
3392 sprintf(str + 5, ".%04d %02d:%02d",
3393 (tm->tm_year > 0) ? tm->tm_year : -(tm->tm_year - 1),
3394 tm->tm_hour, tm->tm_min);
3397 * Print fractional seconds if any. The field widths here should
3398 * be at least equal to MAX_TIMESTAMP_PRECISION.
3400 * In float mode, don't print fractional seconds before 1 AD,
3401 * since it's unlikely there's any precision left ...
3403 #ifdef HAVE_INT64_TIMESTAMP
3406 sprintf(str + strlen(str), ":%02d.%06d", tm->tm_sec, fsec);
3407 TrimTrailingZeros(str);
3410 if (fsec != 0 && tm->tm_year > 0)
3412 sprintf(str + strlen(str), ":%09.6f", tm->tm_sec + fsec);
3413 TrimTrailingZeros(str);
3417 sprintf(str + strlen(str), ":%02d", tm->tm_sec);
3419 if (tzp != NULL && tm->tm_isdst >= 0)
3422 sprintf(str + strlen(str), " %.*s", MAXTZLEN, *tzn);
3424 EncodeTimezone(str, *tzp);
3427 if (tm->tm_year <= 0)
3428 sprintf(str + strlen(str), " BC");
3431 case USE_POSTGRES_DATES:
3433 /* Backward-compatible with traditional Postgres abstime dates */
3435 day = date2j(tm->tm_year, tm->tm_mon, tm->tm_mday);
3436 tm->tm_wday = j2day(day);
3438 strncpy(str, days[tm->tm_wday], 3);
3439 strcpy(str + 3, " ");
3441 if (DateOrder == DATEORDER_DMY)
3442 sprintf(str + 4, "%02d %3s", tm->tm_mday, months[tm->tm_mon - 1]);
3444 sprintf(str + 4, "%3s %02d", months[tm->tm_mon - 1], tm->tm_mday);
3446 sprintf(str + 10, " %02d:%02d", tm->tm_hour, tm->tm_min);
3449 * Print fractional seconds if any. The field widths here should
3450 * be at least equal to MAX_TIMESTAMP_PRECISION.
3452 * In float mode, don't print fractional seconds before 1 AD,
3453 * since it's unlikely there's any precision left ...
3455 #ifdef HAVE_INT64_TIMESTAMP
3458 sprintf(str + strlen(str), ":%02d.%06d", tm->tm_sec, fsec);
3459 TrimTrailingZeros(str);
3462 if (fsec != 0 && tm->tm_year > 0)
3464 sprintf(str + strlen(str), ":%09.6f", tm->tm_sec + fsec);
3465 TrimTrailingZeros(str);
3469 sprintf(str + strlen(str), ":%02d", tm->tm_sec);
3471 sprintf(str + strlen(str), " %04d",
3472 (tm->tm_year > 0) ? tm->tm_year : -(tm->tm_year - 1));
3474 if (tzp != NULL && tm->tm_isdst >= 0)
3477 sprintf(str + strlen(str), " %.*s", MAXTZLEN, *tzn);
3481 * We have a time zone, but no string version. Use the
3482 * numeric form, but be sure to include a leading space to
3483 * avoid formatting something which would be rejected by
3484 * the date/time parser later. - thomas 2001-10-19
3486 sprintf(str + strlen(str), " ");
3487 EncodeTimezone(str, *tzp);
3491 if (tm->tm_year <= 0)
3492 sprintf(str + strlen(str), " BC");
3501 * Interpret time structure as a delta time and convert to string.
3503 * Support "traditional Postgres" and ISO-8601 styles.
3504 * Actually, afaik ISO does not address time interval formatting,
3505 * but this looks similar to the spec for absolute date/time.
3506 * - thomas 1998-04-30
3509 EncodeInterval(struct pg_tm * tm, fsec_t fsec, int style, char *str)
3511 int is_before = FALSE;
3512 int is_nonzero = FALSE;
3516 * The sign of year and month are guaranteed to match, since they are
3517 * stored internally as "month". But we'll need to check for is_before and
3518 * is_nonzero when determining the signs of hour/minute/seconds fields.
3522 /* compatible with ISO date formats */
3524 if (tm->tm_year != 0)
3526 sprintf(cp, "%d year%s",
3527 tm->tm_year, (tm->tm_year != 1) ? "s" : "");
3529 is_before = (tm->tm_year < 0);
3533 if (tm->tm_mon != 0)
3535 sprintf(cp, "%s%s%d mon%s", is_nonzero ? " " : "",
3536 (is_before && tm->tm_mon > 0) ? "+" : "",
3537 tm->tm_mon, (tm->tm_mon != 1) ? "s" : "");
3539 is_before = (tm->tm_mon < 0);
3543 if (tm->tm_mday != 0)
3545 sprintf(cp, "%s%s%d day%s", is_nonzero ? " " : "",
3546 (is_before && tm->tm_mday > 0) ? "+" : "",
3547 tm->tm_mday, (tm->tm_mday != 1) ? "s" : "");
3549 is_before = (tm->tm_mday < 0);
3553 if (!is_nonzero || tm->tm_hour != 0 || tm->tm_min != 0 ||
3554 tm->tm_sec != 0 || fsec != 0)
3556 int minus = (tm->tm_hour < 0 || tm->tm_min < 0 ||
3557 tm->tm_sec < 0 || fsec < 0);
3559 sprintf(cp, "%s%s%02d:%02d", is_nonzero ? " " : "",
3560 (minus ? "-" : (is_before ? "+" : "")),
3561 abs(tm->tm_hour), abs(tm->tm_min));
3563 /* Mark as "non-zero" since the fields are now filled in */
3566 /* need fractional seconds? */
3569 #ifdef HAVE_INT64_TIMESTAMP
3570 sprintf(cp, ":%02d", abs(tm->tm_sec));
3572 sprintf(cp, ".%06d", Abs(fsec));
3575 sprintf(cp, ":%012.9f", fabs(fsec));
3577 TrimTrailingZeros(cp);
3582 sprintf(cp, ":%02d", abs(tm->tm_sec));
3588 case USE_POSTGRES_DATES:
3593 if (tm->tm_year != 0)
3595 int year = tm->tm_year;
3597 if (tm->tm_year < 0)
3600 sprintf(cp, "%d year%s", year,
3601 (year != 1) ? "s" : "");
3603 is_before = (tm->tm_year < 0);
3607 if (tm->tm_mon != 0)
3609 int mon = tm->tm_mon;
3611 if (is_before || (!is_nonzero && tm->tm_mon < 0))
3614 sprintf(cp, "%s%d mon%s", is_nonzero ? " " : "", mon,
3615 (mon != 1) ? "s" : "");
3618 is_before = (tm->tm_mon < 0);
3622 if (tm->tm_mday != 0)
3624 int day = tm->tm_mday;
3626 if (is_before || (!is_nonzero && tm->tm_mday < 0))
3629 sprintf(cp, "%s%d day%s", is_nonzero ? " " : "", day,
3630 (day != 1) ? "s" : "");
3633 is_before = (tm->tm_mday < 0);
3636 if (tm->tm_hour != 0)
3638 int hour = tm->tm_hour;
3640 if (is_before || (!is_nonzero && tm->tm_hour < 0))
3643 sprintf(cp, "%s%d hour%s", is_nonzero ? " " : "", hour,
3644 (hour != 1) ? "s" : "");
3647 is_before = (tm->tm_hour < 0);
3651 if (tm->tm_min != 0)
3653 int min = tm->tm_min;
3655 if (is_before || (!is_nonzero && tm->tm_min < 0))
3658 sprintf(cp, "%s%d min%s", is_nonzero ? " " : "", min,
3659 (min != 1) ? "s" : "");
3662 is_before = (tm->tm_min < 0);
3666 /* fractional seconds? */
3671 #ifdef HAVE_INT64_TIMESTAMP
3673 if (is_before || (!is_nonzero && tm->tm_sec < 0))
3675 tm->tm_sec = -tm->tm_sec;
3679 else if (!is_nonzero && tm->tm_sec == 0 && fsec < 0)
3684 sprintf(cp, "%s%d.%02d secs", is_nonzero ? " " : "",
3685 tm->tm_sec, ((int) sec) / 10000);
3690 if (is_before || (!is_nonzero && fsec < 0))
3693 sprintf(cp, "%s%.2f secs", is_nonzero ? " " : "", sec);
3696 is_before = (fsec < 0);
3700 /* otherwise, integer seconds only? */
3701 else if (tm->tm_sec != 0)
3703 int sec = tm->tm_sec;
3705 if (is_before || (!is_nonzero && tm->tm_sec < 0))
3708 sprintf(cp, "%s%d sec%s", is_nonzero ? " " : "", sec,
3709 (sec != 1) ? "s" : "");
3712 is_before = (tm->tm_sec < 0);
3718 /* identically zero? then put in a unitless zero... */
3725 if (is_before && (style != USE_ISO_DATES))
3732 } /* EncodeInterval() */
3736 * We've been burnt by stupid errors in the ordering of the datetkn tables
3737 * once too often. Arrange to check them during postmaster start.
3740 CheckDateTokenTable(const char *tablename, const datetkn *base, int nel)
3745 for (i = 1; i < nel; i++)
3747 if (strncmp(base[i - 1].token, base[i].token, TOKMAXLEN) >= 0)
3749 elog(LOG, "ordering error in %s table: \"%.*s\" >= \"%.*s\"",
3751 TOKMAXLEN, base[i - 1].token,
3752 TOKMAXLEN, base[i].token);
3760 CheckDateTokenTables(void)
3764 Assert(UNIX_EPOCH_JDATE == date2j(1970, 1, 1));
3765 Assert(POSTGRES_EPOCH_JDATE == date2j(2000, 1, 1));
3767 ok &= CheckDateTokenTable("datetktbl", datetktbl, szdatetktbl);
3768 ok &= CheckDateTokenTable("deltatktbl", deltatktbl, szdeltatktbl);
3773 * This function gets called during timezone config file load or reload
3774 * to create the final array of timezone tokens. The argument array
3775 * is already sorted in name order. This data is in a temporary memory
3776 * context and must be copied to somewhere permanent.
3779 InstallTimeZoneAbbrevs(tzEntry *abbrevs, int n)
3785 * Copy the data into TopMemoryContext and convert to datetkn format.
3787 newtbl = (datetkn *) MemoryContextAlloc(TopMemoryContext,
3788 n * sizeof(datetkn));
3789 for (i = 0; i < n; i++)
3791 strncpy(newtbl[i].token, abbrevs[i].abbrev, TOKMAXLEN);
3792 newtbl[i].type = abbrevs[i].is_dst ? DTZ : TZ;
3793 TOVAL(&newtbl[i], abbrevs[i].offset / 60);
3796 /* Check the ordering, if testing */
3797 Assert(CheckDateTokenTable("timezone offset", newtbl, n));
3799 /* Now safe to replace existing table (if any) */
3801 pfree(timezonetktbl);
3802 timezonetktbl = newtbl;
3803 sztimezonetktbl = n;
3805 /* clear date cache in case it contains any stale timezone names */
3806 for (i = 0; i < MAXDATEFIELDS; i++)
3807 datecache[i] = NULL;
3811 * This set-returning function reads all the available time zone abbreviations
3812 * and returns a set of (abbrev, utc_offset, is_dst).
3815 pg_timezone_abbrevs(PG_FUNCTION_ARGS)
3817 FuncCallContext *funcctx;
3823 char buffer[TOKMAXLEN + 1];
3826 Interval *resInterval;
3828 /* stuff done only on the first call of the function */
3829 if (SRF_IS_FIRSTCALL())
3832 MemoryContext oldcontext;
3834 /* create a function context for cross-call persistence */
3835 funcctx = SRF_FIRSTCALL_INIT();
3838 * switch to memory context appropriate for multiple function calls
3840 oldcontext = MemoryContextSwitchTo(funcctx->multi_call_memory_ctx);
3842 /* allocate memory for user context */
3843 pindex = (int *) palloc(sizeof(int));
3845 funcctx->user_fctx = (void *) pindex;
3848 * build tupdesc for result tuples. This must match this function's
3851 tupdesc = CreateTemplateTupleDesc(3, false);
3852 TupleDescInitEntry(tupdesc, (AttrNumber) 1, "abbrev",
3854 TupleDescInitEntry(tupdesc, (AttrNumber) 2, "utc_offset",
3855 INTERVALOID, -1, 0);
3856 TupleDescInitEntry(tupdesc, (AttrNumber) 3, "is_dst",
3859 funcctx->tuple_desc = BlessTupleDesc(tupdesc);
3860 MemoryContextSwitchTo(oldcontext);
3863 /* stuff done on every call of the function */
3864 funcctx = SRF_PERCALL_SETUP();
3865 pindex = (int *) funcctx->user_fctx;
3867 if (*pindex >= sztimezonetktbl)
3868 SRF_RETURN_DONE(funcctx);
3870 MemSet(nulls, 0, sizeof(nulls));
3873 * Convert name to text, using upcasing conversion that is the inverse of
3874 * what ParseDateTime() uses.
3876 strncpy(buffer, timezonetktbl[*pindex].token, TOKMAXLEN);
3877 buffer[TOKMAXLEN] = '\0'; /* may not be null-terminated */
3878 for (p = (unsigned char *) buffer; *p; p++)
3879 *p = pg_toupper(*p);
3881 values[0] = DirectFunctionCall1(textin, CStringGetDatum(buffer));
3883 MemSet(&tm, 0, sizeof(struct pg_tm));
3884 tm.tm_min = (-1) * FROMVAL(&timezonetktbl[*pindex]);
3885 resInterval = (Interval *) palloc(sizeof(Interval));
3886 tm2interval(&tm, 0, resInterval);
3887 values[1] = IntervalPGetDatum(resInterval);
3889 Assert(timezonetktbl[*pindex].type == DTZ ||
3890 timezonetktbl[*pindex].type == TZ);
3891 values[2] = BoolGetDatum(timezonetktbl[*pindex].type == DTZ);
3895 tuple = heap_form_tuple(funcctx->tuple_desc, values, nulls);
3896 result = HeapTupleGetDatum(tuple);
3898 SRF_RETURN_NEXT(funcctx, result);
3902 * This set-returning function reads all the available full time zones
3903 * and returns a set of (name, abbrev, utc_offset, is_dst).
3906 pg_timezone_names(PG_FUNCTION_ARGS)
3908 MemoryContext oldcontext;
3909 FuncCallContext *funcctx;
3920 Interval *resInterval;
3923 /* stuff done only on the first call of the function */
3924 if (SRF_IS_FIRSTCALL())
3928 /* create a function context for cross-call persistence */
3929 funcctx = SRF_FIRSTCALL_INIT();
3932 * switch to memory context appropriate for multiple function calls
3934 oldcontext = MemoryContextSwitchTo(funcctx->multi_call_memory_ctx);
3936 /* initialize timezone scanning code */
3937 tzenum = pg_tzenumerate_start();
3938 funcctx->user_fctx = (void *) tzenum;
3941 * build tupdesc for result tuples. This must match this function's
3944 tupdesc = CreateTemplateTupleDesc(4, false);
3945 TupleDescInitEntry(tupdesc, (AttrNumber) 1, "name",
3947 TupleDescInitEntry(tupdesc, (AttrNumber) 2, "abbrev",
3949 TupleDescInitEntry(tupdesc, (AttrNumber) 3, "utc_offset",
3950 INTERVALOID, -1, 0);
3951 TupleDescInitEntry(tupdesc, (AttrNumber) 4, "is_dst",
3954 funcctx->tuple_desc = BlessTupleDesc(tupdesc);
3955 MemoryContextSwitchTo(oldcontext);
3958 /* stuff done on every call of the function */
3959 funcctx = SRF_PERCALL_SETUP();
3960 tzenum = (pg_tzenum *) funcctx->user_fctx;
3962 /* search for another zone to display */
3965 oldcontext = MemoryContextSwitchTo(funcctx->multi_call_memory_ctx);
3966 tz = pg_tzenumerate_next(tzenum);
3967 MemoryContextSwitchTo(oldcontext);
3971 pg_tzenumerate_end(tzenum);
3972 funcctx->user_fctx = NULL;
3973 SRF_RETURN_DONE(funcctx);
3976 /* Convert now() to local time in this zone */
3977 if (timestamp2tm(GetCurrentTransactionStartTimestamp(),
3978 &tzoff, &tm, &fsec, &tzn, tz) != 0)
3979 continue; /* ignore if conversion fails */
3981 /* Ignore zic's rather silly "Factory" time zone */
3982 if (tzn && strcmp(tzn, "Local time zone must be set--see zic manual page") == 0)
3985 /* Found a displayable zone */
3989 MemSet(nulls, 0, sizeof(nulls));
3991 values[0] = DirectFunctionCall1(textin,
3992 CStringGetDatum(pg_get_timezone_name(tz)));
3994 values[1] = DirectFunctionCall1(textin,
3995 CStringGetDatum(tzn ? tzn : ""));
3997 MemSet(&itm, 0, sizeof(struct pg_tm));
3998 itm.tm_sec = -tzoff;
3999 resInterval = (Interval *) palloc(sizeof(Interval));
4000 tm2interval(&itm, 0, resInterval);
4001 values[2] = IntervalPGetDatum(resInterval);
4003 values[3] = BoolGetDatum(tm.tm_isdst > 0);
4005 tuple = heap_form_tuple(funcctx->tuple_desc, values, nulls);
4006 result = HeapTupleGetDatum(tuple);
4008 SRF_RETURN_NEXT(funcctx, result);