1 /*-------------------------------------------------------------------------
4 * Support functions for date/time types.
6 * Portions Copyright (c) 1996-2008, 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.184 2008/01/01 19:45:52 momjian 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, bool *is2digits);
36 static int DecodeNumberField(int len, char *str,
37 int fmask, int *tmask,
38 struct pg_tm * tm, fsec_t *fsec, bool *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 {"isodow", RESERV, DTK_ISODOW}, /* ISO day of week, Sunday == 7 */
129 {"isoyear", UNITS, DTK_ISOYEAR}, /* year in terms of the ISO week date */
130 {"j", UNITS, DTK_JULIAN},
132 {"january", MONTH, 1},
133 {"jd", UNITS, DTK_JULIAN},
135 {"julian", UNITS, DTK_JULIAN},
139 {"m", UNITS, DTK_MONTH}, /* "month" for ISO input */
143 {"mm", UNITS, DTK_MINUTE}, /* "minute" for ISO input */
147 {"november", MONTH, 11},
148 {NOW, RESERV, DTK_NOW}, /* current transaction time */
150 {"october", MONTH, 10},
151 {"on", IGNORE_DTF, 0}, /* "on" (throwaway) */
153 {"s", UNITS, DTK_SECOND}, /* "seconds" for ISO input */
155 {"saturday", DOW, 6},
158 {"september", MONTH, 9},
161 {"t", ISOTIME, DTK_TIME}, /* Filler for ISO time fields */
165 {"thursday", DOW, 4},
166 {TODAY, RESERV, DTK_TODAY}, /* midnight */
167 {TOMORROW, RESERV, DTK_TOMORROW}, /* tomorrow midnight */
171 {"undefined", RESERV, DTK_INVALID}, /* pre-v6.1 invalid time */
173 {"wednesday", DOW, 3},
175 {"y", UNITS, DTK_YEAR}, /* "year" for ISO input */
176 {YESTERDAY, RESERV, DTK_YESTERDAY} /* yesterday midnight */
179 static int szdatetktbl = sizeof datetktbl / sizeof datetktbl[0];
181 static datetkn deltatktbl[] = {
182 /* text, token, lexval */
183 {"@", IGNORE_DTF, 0}, /* postgres relative prefix */
184 {DAGO, AGO, 0}, /* "ago" indicates negative time offset */
185 {"c", UNITS, DTK_CENTURY}, /* "century" relative */
186 {"cent", UNITS, DTK_CENTURY}, /* "century" relative */
187 {"centuries", UNITS, DTK_CENTURY}, /* "centuries" relative */
188 {DCENTURY, UNITS, DTK_CENTURY}, /* "century" relative */
189 {"d", UNITS, DTK_DAY}, /* "day" relative */
190 {DDAY, UNITS, DTK_DAY}, /* "day" relative */
191 {"days", UNITS, DTK_DAY}, /* "days" relative */
192 {"dec", UNITS, DTK_DECADE}, /* "decade" relative */
193 {DDECADE, UNITS, DTK_DECADE}, /* "decade" relative */
194 {"decades", UNITS, DTK_DECADE}, /* "decades" relative */
195 {"decs", UNITS, DTK_DECADE}, /* "decades" relative */
196 {"h", UNITS, DTK_HOUR}, /* "hour" relative */
197 {DHOUR, UNITS, DTK_HOUR}, /* "hour" relative */
198 {"hours", UNITS, DTK_HOUR}, /* "hours" relative */
199 {"hr", UNITS, DTK_HOUR}, /* "hour" relative */
200 {"hrs", UNITS, DTK_HOUR}, /* "hours" relative */
201 {INVALID, RESERV, DTK_INVALID}, /* reserved for invalid time */
202 {"m", UNITS, DTK_MINUTE}, /* "minute" relative */
203 {"microsecon", UNITS, DTK_MICROSEC}, /* "microsecond" relative */
204 {"mil", UNITS, DTK_MILLENNIUM}, /* "millennium" relative */
205 {"millennia", UNITS, DTK_MILLENNIUM}, /* "millennia" relative */
206 {DMILLENNIUM, UNITS, DTK_MILLENNIUM}, /* "millennium" relative */
207 {"millisecon", UNITS, DTK_MILLISEC}, /* relative */
208 {"mils", UNITS, DTK_MILLENNIUM}, /* "millennia" relative */
209 {"min", UNITS, DTK_MINUTE}, /* "minute" relative */
210 {"mins", UNITS, DTK_MINUTE}, /* "minutes" relative */
211 {DMINUTE, UNITS, DTK_MINUTE}, /* "minute" relative */
212 {"minutes", UNITS, DTK_MINUTE}, /* "minutes" relative */
213 {"mon", UNITS, DTK_MONTH}, /* "months" relative */
214 {"mons", UNITS, DTK_MONTH}, /* "months" relative */
215 {DMONTH, UNITS, DTK_MONTH}, /* "month" relative */
216 {"months", UNITS, DTK_MONTH},
217 {"ms", UNITS, DTK_MILLISEC},
218 {"msec", UNITS, DTK_MILLISEC},
219 {DMILLISEC, UNITS, DTK_MILLISEC},
220 {"mseconds", UNITS, DTK_MILLISEC},
221 {"msecs", UNITS, DTK_MILLISEC},
222 {"qtr", UNITS, DTK_QUARTER}, /* "quarter" relative */
223 {DQUARTER, UNITS, DTK_QUARTER}, /* "quarter" relative */
224 {"reltime", IGNORE_DTF, 0}, /* pre-v6.1 "Undefined Reltime" */
225 {"s", UNITS, DTK_SECOND},
226 {"sec", UNITS, DTK_SECOND},
227 {DSECOND, UNITS, DTK_SECOND},
228 {"seconds", UNITS, DTK_SECOND},
229 {"secs", UNITS, DTK_SECOND},
230 {DTIMEZONE, UNITS, DTK_TZ}, /* "timezone" time offset */
231 {"timezone_h", UNITS, DTK_TZ_HOUR}, /* timezone hour units */
232 {"timezone_m", UNITS, DTK_TZ_MINUTE}, /* timezone minutes units */
233 {"undefined", RESERV, DTK_INVALID}, /* pre-v6.1 invalid time */
234 {"us", UNITS, DTK_MICROSEC}, /* "microsecond" relative */
235 {"usec", UNITS, DTK_MICROSEC}, /* "microsecond" relative */
236 {DMICROSEC, UNITS, DTK_MICROSEC}, /* "microsecond" relative */
237 {"useconds", UNITS, DTK_MICROSEC}, /* "microseconds" relative */
238 {"usecs", UNITS, DTK_MICROSEC}, /* "microseconds" relative */
239 {"w", UNITS, DTK_WEEK}, /* "week" relative */
240 {DWEEK, UNITS, DTK_WEEK}, /* "week" relative */
241 {"weeks", UNITS, DTK_WEEK}, /* "weeks" relative */
242 {"y", UNITS, DTK_YEAR}, /* "year" relative */
243 {DYEAR, UNITS, DTK_YEAR}, /* "year" relative */
244 {"years", UNITS, DTK_YEAR}, /* "years" relative */
245 {"yr", UNITS, DTK_YEAR}, /* "year" relative */
246 {"yrs", UNITS, DTK_YEAR} /* "years" relative */
249 static int szdeltatktbl = sizeof deltatktbl / sizeof deltatktbl[0];
251 static const datetkn *datecache[MAXDATEFIELDS] = {NULL};
253 static const datetkn *deltacache[MAXDATEFIELDS] = {NULL};
257 * Calendar time to Julian date conversions.
258 * Julian date is commonly used in astronomical applications,
259 * since it is numerically accurate and computationally simple.
260 * The algorithms here will accurately convert between Julian day
261 * and calendar date for all non-negative Julian days
262 * (i.e. from Nov 24, -4713 on).
264 * These routines will be used by other date/time packages
267 * Rewritten to eliminate overflow problems. This now allows the
268 * routines to work correctly for all Julian day counts from
269 * 0 to 2147483647 (Nov 24, -4713 to Jun 3, 5874898) assuming
270 * a 32-bit integer. Longer types should also work to the limits
271 * of their precision.
275 date2j(int y, int m, int d)
292 julian = y * 365 - 32167;
293 julian += y / 4 - century + century / 4;
294 julian += 7834 * m / 256 + d;
300 j2date(int jd, int *year, int *month, int *day)
309 quad = julian / 146097;
310 extra = (julian - quad * 146097) * 4 + 3;
311 julian += 60 + quad * 3 + extra / 146097;
312 quad = julian / 1461;
313 julian -= quad * 1461;
314 y = julian * 4 / 1461;
315 julian = ((y != 0) ? ((julian + 305) % 365) : ((julian + 306) % 366))
319 quad = julian * 2141 / 65536;
320 *day = julian - 7834 * quad / 256;
321 *month = (quad + 10) % 12 + 1;
328 * j2day - convert Julian date to day-of-week (0..6 == Sun..Sat)
330 * Note: various places use the locution j2day(date - 1) to produce a
331 * result according to the convention 0..6 = Mon..Sun. This is a bit of
332 * a crock, but will work as long as the computation here is just a modulo.
349 * GetCurrentDateTime()
351 * Get the transaction start time ("now()") broken down as a struct pg_tm.
354 GetCurrentDateTime(struct pg_tm * tm)
359 timestamp2tm(GetCurrentTransactionStartTimestamp(), &tz, tm, &fsec,
361 /* Note: don't pass NULL tzp to timestamp2tm; affects behavior */
365 * GetCurrentTimeUsec()
367 * Get the transaction start time ("now()") broken down as a struct pg_tm,
368 * including fractional seconds and timezone offset.
371 GetCurrentTimeUsec(struct pg_tm * tm, fsec_t *fsec, int *tzp)
375 timestamp2tm(GetCurrentTransactionStartTimestamp(), &tz, tm, fsec,
377 /* Note: don't pass NULL tzp to timestamp2tm; affects behavior */
383 /* TrimTrailingZeros()
384 * ... resulting from printing numbers with full precision.
387 TrimTrailingZeros(char *str)
389 int len = strlen(str);
392 /* chop off trailing one to cope with interval rounding */
393 if (strcmp(str + len - 4, "0001") == 0)
400 /* chop off trailing zeros... but leave at least 2 fractional digits */
401 while (*(str + len - 1) == '0' && *(str + len - 3) != '.')
409 * Break string into tokens based on a date/time context.
410 * Returns 0 if successful, DTERR code if bogus input detected.
412 * timestr - the input string
413 * workbuf - workspace for field string storage. This must be
414 * larger than the largest legal input for this datetime type --
415 * some additional space will be needed to NUL terminate fields.
416 * buflen - the size of workbuf
417 * field[] - pointers to field strings are returned in this array
418 * ftype[] - field type indicators are returned in this array
419 * maxfields - dimensions of the above two arrays
420 * *numfields - set to the actual number of fields detected
422 * The fields extracted from the input are stored as separate,
423 * null-terminated strings in the workspace at workbuf. Any text is
424 * converted to lower case.
426 * Several field types are assigned:
427 * DTK_NUMBER - digits and (possibly) a decimal point
428 * DTK_DATE - digits and two delimiters, or digits and text
429 * DTK_TIME - digits, colon delimiters, and possibly a decimal point
430 * DTK_STRING - text (no digits or punctuation)
431 * DTK_SPECIAL - leading "+" or "-" followed by text
432 * DTK_TZ - leading "+" or "-" followed by digits (also eats ':' or '.')
434 * Note that some field types can hold unexpected items:
435 * DTK_NUMBER can hold date fields (yy.ddd)
436 * DTK_STRING can hold months (January) and time zones (PST)
437 * DTK_DATE can hold time zone names (America/New_York, GMT-8)
440 ParseDateTime(const char *timestr, char *workbuf, size_t buflen,
441 char **field, int *ftype, int maxfields, int *numfields)
444 const char *cp = timestr;
445 char *bufp = workbuf;
446 const char *bufend = workbuf + buflen;
449 * Set the character pointed-to by "bufptr" to "newchar", and increment
450 * "bufptr". "end" gives the end of the buffer -- we return an error if
451 * there is no space left to append a character to the buffer. Note that
452 * "bufptr" is evaluated twice.
454 #define APPEND_CHAR(bufptr, end, newchar) \
457 if (((bufptr) + 1) >= (end)) \
458 return DTERR_BAD_FORMAT; \
459 *(bufptr)++ = newchar; \
462 /* outer loop through fields */
465 /* Ignore spaces between fields */
466 if (isspace((unsigned char) *cp))
472 /* Record start of current field */
474 return DTERR_BAD_FORMAT;
477 /* leading digit? then date or time */
478 if (isdigit((unsigned char) *cp))
480 APPEND_CHAR(bufp, bufend, *cp++);
481 while (isdigit((unsigned char) *cp))
482 APPEND_CHAR(bufp, bufend, *cp++);
487 ftype[nf] = DTK_TIME;
488 APPEND_CHAR(bufp, bufend, *cp++);
489 while (isdigit((unsigned char) *cp) ||
490 (*cp == ':') || (*cp == '.'))
491 APPEND_CHAR(bufp, bufend, *cp++);
493 /* date field? allow embedded text month */
494 else if (*cp == '-' || *cp == '/' || *cp == '.')
496 /* save delimiting character to use later */
499 APPEND_CHAR(bufp, bufend, *cp++);
500 /* second field is all digits? then no embedded text month */
501 if (isdigit((unsigned char) *cp))
503 ftype[nf] = ((delim == '.') ? DTK_NUMBER : DTK_DATE);
504 while (isdigit((unsigned char) *cp))
505 APPEND_CHAR(bufp, bufend, *cp++);
508 * insist that the delimiters match to get a three-field
513 ftype[nf] = DTK_DATE;
514 APPEND_CHAR(bufp, bufend, *cp++);
515 while (isdigit((unsigned char) *cp) || *cp == delim)
516 APPEND_CHAR(bufp, bufend, *cp++);
521 ftype[nf] = DTK_DATE;
522 while (isalnum((unsigned char) *cp) || *cp == delim)
523 APPEND_CHAR(bufp, bufend, pg_tolower((unsigned char) *cp++));
528 * otherwise, number only and will determine year, month, day, or
529 * concatenated fields later...
532 ftype[nf] = DTK_NUMBER;
534 /* Leading decimal point? Then fractional seconds... */
537 APPEND_CHAR(bufp, bufend, *cp++);
538 while (isdigit((unsigned char) *cp))
539 APPEND_CHAR(bufp, bufend, *cp++);
541 ftype[nf] = DTK_NUMBER;
545 * text? then date string, month, day of week, special, or timezone
547 else if (isalpha((unsigned char) *cp))
551 ftype[nf] = DTK_STRING;
552 APPEND_CHAR(bufp, bufend, pg_tolower((unsigned char) *cp++));
553 while (isalpha((unsigned char) *cp))
554 APPEND_CHAR(bufp, bufend, pg_tolower((unsigned char) *cp++));
557 * Dates can have embedded '-', '/', or '.' separators. It could
558 * also be a timezone name containing embedded '/', '+', '-', '_',
559 * or ':' (but '_' or ':' can't be the first punctuation). If the
560 * next character is a digit or '+', we need to check whether what
561 * we have so far is a recognized non-timezone keyword --- if so,
562 * don't believe that this is the start of a timezone.
565 if (*cp == '-' || *cp == '/' || *cp == '.')
567 else if (*cp == '+' || isdigit((unsigned char) *cp))
569 *bufp = '\0'; /* null-terminate current field value */
570 /* we need search only the core token table, not TZ names */
571 if (datebsearch(field[nf], datetktbl, szdatetktbl) == NULL)
576 ftype[nf] = DTK_DATE;
579 APPEND_CHAR(bufp, bufend, pg_tolower((unsigned char) *cp++));
580 } while (*cp == '+' || *cp == '-' ||
581 *cp == '/' || *cp == '_' ||
582 *cp == '.' || *cp == ':' ||
583 isalnum((unsigned char) *cp));
586 /* sign? then special or numeric timezone */
587 else if (*cp == '+' || *cp == '-')
589 APPEND_CHAR(bufp, bufend, *cp++);
590 /* soak up leading whitespace */
591 while (isspace((unsigned char) *cp))
593 /* numeric timezone? */
594 if (isdigit((unsigned char) *cp))
597 APPEND_CHAR(bufp, bufend, *cp++);
598 while (isdigit((unsigned char) *cp) ||
599 *cp == ':' || *cp == '.')
600 APPEND_CHAR(bufp, bufend, *cp++);
603 else if (isalpha((unsigned char) *cp))
605 ftype[nf] = DTK_SPECIAL;
606 APPEND_CHAR(bufp, bufend, pg_tolower((unsigned char) *cp++));
607 while (isalpha((unsigned char) *cp))
608 APPEND_CHAR(bufp, bufend, pg_tolower((unsigned char) *cp++));
610 /* otherwise something wrong... */
612 return DTERR_BAD_FORMAT;
614 /* ignore other punctuation but use as delimiter */
615 else if (ispunct((unsigned char) *cp))
620 /* otherwise, something is not right... */
622 return DTERR_BAD_FORMAT;
624 /* force in a delimiter after each field */
636 * Interpret previously parsed fields for general date and time.
637 * Return 0 if full date, 1 if only time, and negative DTERR code if problems.
638 * (Currently, all callers treat 1 as an error return too.)
640 * External format(s):
641 * "<weekday> <month>-<day>-<year> <hour>:<minute>:<second>"
642 * "Fri Feb-7-1997 15:23:27"
643 * "Feb-7-1997 15:23:27"
644 * "2-7-1997 15:23:27"
645 * "1997-2-7 15:23:27"
646 * "1997.038 15:23:27" (day of year 1-366)
647 * Also supports input in compact time:
650 * "20011225T040506.789-07"
652 * Use the system-provided functions to get the current time zone
653 * if not specified in the input string.
654 * If the date is outside the time_t system-supported time range,
655 * then assume UTC time zone. - thomas 1997-05-27
658 DecodeDateTime(char **field, int *ftype, int nf,
659 int *dtype, struct pg_tm * tm, fsec_t *fsec, int *tzp)
664 int ptype = 0; /* "prefix type" for ISO y2001m02d04 format */
669 bool haveTextMonth = FALSE;
670 bool is2digits = FALSE;
672 pg_tz *namedTz = NULL;
675 * We'll insist on at least all of the date fields, but initialize the
676 * remaining fields in case they are not set later...
683 /* don't know daylight savings time status apriori */
688 for (i = 0; i < nf; i++)
694 * Integral julian day with attached time zone?
695 * All other forms with JD will be separated into
696 * distinct fields, so we handle just this case here.
698 if (ptype == DTK_JULIAN)
704 return DTERR_BAD_FORMAT;
707 val = strtol(field[i], &cp, 10);
709 return DTERR_FIELD_OVERFLOW;
711 j2date(val, &tm->tm_year, &tm->tm_mon, &tm->tm_mday);
712 /* Get the time zone from the end of the string */
713 dterr = DecodeTimezone(cp, tzp);
717 tmask = DTK_DATE_M | DTK_TIME_M | DTK_M(TZ);
722 * Already have a date? Then this might be a time zone name
723 * with embedded punctuation (e.g. "America/New_York") or a
724 * run-together time with trailing time zone (e.g. hhmmss-zz).
725 * - thomas 2001-12-25
727 * We consider it a time zone if we already have month & day.
728 * This is to allow the form "mmm dd hhmmss tz year", which
729 * we've historically accepted.
731 else if (ptype != 0 ||
732 ((fmask & (DTK_M(MONTH) | DTK_M(DAY))) ==
733 (DTK_M(MONTH) | DTK_M(DAY))))
735 /* No time zone accepted? Then quit... */
737 return DTERR_BAD_FORMAT;
739 if (isdigit((unsigned char) *field[i]) || ptype != 0)
745 /* Sanity check; should not fail this test */
746 if (ptype != DTK_TIME)
747 return DTERR_BAD_FORMAT;
752 * Starts with a digit but we already have a time
753 * field? Then we are in trouble with a date and time
756 if ((fmask & DTK_TIME_M) == DTK_TIME_M)
757 return DTERR_BAD_FORMAT;
759 if ((cp = strchr(field[i], '-')) == NULL)
760 return DTERR_BAD_FORMAT;
762 /* Get the time zone from the end of the string */
763 dterr = DecodeTimezone(cp, tzp);
769 * Then read the rest of the field as a concatenated
772 dterr = DecodeNumberField(strlen(field[i]), field[i],
780 * modify tmask after returning from
781 * DecodeNumberField()
787 namedTz = pg_tzset(field[i]);
791 * We should return an error code instead of
792 * ereport'ing directly, but then there is no way
793 * to report the bad time zone name.
796 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
797 errmsg("time zone \"%s\" not recognized",
800 /* we'll apply the zone setting below */
806 dterr = DecodeDate(field[i], fmask, &tmask, tm);
813 dterr = DecodeTime(field[i], fmask, &tmask, tm, fsec);
818 * Check upper limit on hours; other limits checked in
821 /* test for > 24:00:00 */
822 if (tm->tm_hour > 24 ||
823 (tm->tm_hour == 24 && (tm->tm_min > 0 || tm->tm_sec > 0)))
824 return DTERR_FIELD_OVERFLOW;
832 return DTERR_BAD_FORMAT;
834 dterr = DecodeTimezone(field[i], &tz);
845 * Was this an "ISO date" with embedded field labels? An
846 * example is "y2001m02d04" - thomas 2001-02-04
854 val = strtol(field[i], &cp, 10);
856 return DTERR_FIELD_OVERFLOW;
859 * only a few kinds are allowed to have an embedded
870 return DTERR_BAD_FORMAT;
873 else if (*cp != '\0')
874 return DTERR_BAD_FORMAT;
886 * already have a month and hour? then assume
889 if ((fmask & DTK_M(MONTH)) != 0 &&
890 (fmask & DTK_M(HOUR)) != 0)
893 tmask = DTK_M(MINUTE);
898 tmask = DTK_M(MONTH);
914 tmask = DTK_M(MINUTE);
919 tmask = DTK_M(SECOND);
924 frac = strtod(cp, &cp);
926 return DTERR_BAD_FORMAT;
927 #ifdef HAVE_INT64_TIMESTAMP
928 *fsec = rint(frac * 1000000);
932 tmask = DTK_ALL_SECS_M;
938 dterr = DecodeTimezone(field[i], tzp);
945 * previous field was a label for "julian date"?
948 j2date(val, &tm->tm_year, &tm->tm_mon, &tm->tm_mday);
949 /* fractional Julian Day? */
954 time = strtod(cp, &cp);
956 return DTERR_BAD_FORMAT;
959 #ifdef HAVE_INT64_TIMESTAMP
960 dt2time(time * USECS_PER_DAY,
961 &tm->tm_hour, &tm->tm_min,
964 dt2time(time * SECS_PER_DAY, &tm->tm_hour,
965 &tm->tm_min, &tm->tm_sec, fsec);
971 /* previous field was "t" for ISO time */
972 dterr = DecodeNumberField(strlen(field[i]), field[i],
973 (fmask | DTK_DATE_M),
978 if (tmask != DTK_TIME_M)
979 return DTERR_BAD_FORMAT;
983 return DTERR_BAD_FORMAT;
995 flen = strlen(field[i]);
996 cp = strchr(field[i], '.');
998 /* Embedded decimal and no date yet? */
999 if (cp != NULL && !(fmask & DTK_DATE_M))
1001 dterr = DecodeDate(field[i], fmask, &tmask, tm);
1005 /* embedded decimal and several digits before? */
1006 else if (cp != NULL && flen - strlen(cp) > 2)
1009 * Interpret as a concatenated date or time Set the
1010 * type field to allow decoding other fields later.
1011 * Example: 20011223 or 040506
1013 dterr = DecodeNumberField(flen, field[i], fmask,
1021 dterr = DecodeNumberField(flen, field[i], fmask,
1027 /* otherwise it is a single date/time field... */
1030 dterr = DecodeNumber(flen, field[i],
1031 haveTextMonth, fmask,
1042 type = DecodeSpecial(i, field[i], &val);
1043 if (type == IGNORE_DTF)
1046 tmask = DTK_M(type);
1054 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1055 errmsg("date/time value \"current\" is no longer supported")));
1057 return DTERR_BAD_FORMAT;
1061 tmask = (DTK_DATE_M | DTK_TIME_M | DTK_M(TZ));
1063 GetCurrentTimeUsec(tm, fsec, tzp);
1069 GetCurrentDateTime(tm);
1070 j2date(date2j(tm->tm_year, tm->tm_mon, tm->tm_mday) - 1,
1071 &tm->tm_year, &tm->tm_mon, &tm->tm_mday);
1080 GetCurrentDateTime(tm);
1089 GetCurrentDateTime(tm);
1090 j2date(date2j(tm->tm_year, tm->tm_mon, tm->tm_mday) + 1,
1091 &tm->tm_year, &tm->tm_mon, &tm->tm_mday);
1098 tmask = (DTK_TIME_M | DTK_M(TZ));
1116 * already have a (numeric) month? then see if we can
1119 if ((fmask & DTK_M(MONTH)) && !haveTextMonth &&
1120 !(fmask & DTK_M(DAY)) && tm->tm_mon >= 1 &&
1123 tm->tm_mday = tm->tm_mon;
1126 haveTextMonth = TRUE;
1133 * daylight savings time modifier (solves "MET DST"
1136 tmask |= DTK_M(DTZ);
1139 return DTERR_BAD_FORMAT;
1140 *tzp += val * MINS_PER_HOUR;
1146 * set mask for TZ here _or_ check for DTZ later when
1147 * getting default timezone
1152 return DTERR_BAD_FORMAT;
1153 *tzp = val * MINS_PER_HOUR;
1159 return DTERR_BAD_FORMAT;
1160 *tzp = val * MINS_PER_HOUR;
1186 * This is a filler field "t" indicating that the next
1187 * field is time. Try to verify that this is sensible.
1191 /* No preceding date? Then quit... */
1192 if ((fmask & DTK_DATE_M) != DTK_DATE_M)
1193 return DTERR_BAD_FORMAT;
1196 * We will need one of the following fields:
1197 * DTK_NUMBER should be hhmmss.fff
1198 * DTK_TIME should be hh:mm:ss.fff
1199 * DTK_DATE should be hhmmss-zz
1202 (ftype[i + 1] != DTK_NUMBER &&
1203 ftype[i + 1] != DTK_TIME &&
1204 ftype[i + 1] != DTK_DATE))
1205 return DTERR_BAD_FORMAT;
1213 * Before giving up and declaring error, check to see
1214 * if it is an all-alpha timezone name.
1216 namedTz = pg_tzset(field[i]);
1218 return DTERR_BAD_FORMAT;
1219 /* we'll apply the zone setting below */
1224 return DTERR_BAD_FORMAT;
1229 return DTERR_BAD_FORMAT;
1233 return DTERR_BAD_FORMAT;
1237 if (fmask & DTK_M(YEAR))
1239 /* there is no year zero in AD/BC notation; i.e. "1 BC" == year 0 */
1242 if (tm->tm_year > 0)
1243 tm->tm_year = -(tm->tm_year - 1);
1246 (errcode(ERRCODE_INVALID_DATETIME_FORMAT),
1247 errmsg("inconsistent use of year %04d and \"BC\"",
1252 if (tm->tm_year < 70)
1253 tm->tm_year += 2000;
1254 else if (tm->tm_year < 100)
1255 tm->tm_year += 1900;
1259 /* now that we have correct year, decode DOY */
1260 if (fmask & DTK_M(DOY))
1262 j2date(date2j(tm->tm_year, 1, 1) + tm->tm_yday - 1,
1263 &tm->tm_year, &tm->tm_mon, &tm->tm_mday);
1266 /* check for valid month */
1267 if (fmask & DTK_M(MONTH))
1269 if (tm->tm_mon < 1 || tm->tm_mon > MONTHS_PER_YEAR)
1270 return DTERR_MD_FIELD_OVERFLOW;
1273 /* minimal check for valid day */
1274 if (fmask & DTK_M(DAY))
1276 if (tm->tm_mday < 1 || tm->tm_mday > 31)
1277 return DTERR_MD_FIELD_OVERFLOW;
1280 if (mer != HR24 && tm->tm_hour > 12)
1281 return DTERR_FIELD_OVERFLOW;
1282 if (mer == AM && tm->tm_hour == 12)
1284 else if (mer == PM && tm->tm_hour != 12)
1287 /* do additional checking for full date specs... */
1288 if (*dtype == DTK_DATE)
1290 if ((fmask & DTK_DATE_M) != DTK_DATE_M)
1292 if ((fmask & DTK_TIME_M) == DTK_TIME_M)
1294 return DTERR_BAD_FORMAT;
1298 * Check for valid day of month, now that we know for sure the month
1299 * and year. Note we don't use MD_FIELD_OVERFLOW here, since it seems
1300 * unlikely that "Feb 29" is a YMD-order error.
1302 if (tm->tm_mday > day_tab[isleap(tm->tm_year)][tm->tm_mon - 1])
1303 return DTERR_FIELD_OVERFLOW;
1306 * If we had a full timezone spec, compute the offset (we could not do
1307 * it before, because we need the date to resolve DST status).
1309 if (namedTz != NULL)
1311 /* daylight savings time modifier disallowed with full TZ */
1312 if (fmask & DTK_M(DTZMOD))
1313 return DTERR_BAD_FORMAT;
1315 *tzp = DetermineTimeZoneOffset(tm, namedTz);
1318 /* timezone not specified? then find local timezone if possible */
1319 if (tzp != NULL && !(fmask & DTK_M(TZ)))
1322 * daylight savings time modifier but no standard timezone? then
1325 if (fmask & DTK_M(DTZMOD))
1326 return DTERR_BAD_FORMAT;
1328 *tzp = DetermineTimeZoneOffset(tm, session_timezone);
1336 /* DetermineTimeZoneOffset()
1338 * Given a struct pg_tm in which tm_year, tm_mon, tm_mday, tm_hour, tm_min, and
1339 * tm_sec fields are set, attempt to determine the applicable time zone
1340 * (ie, regular or daylight-savings time) at that time. Set the struct pg_tm's
1341 * tm_isdst field accordingly, and return the actual timezone offset.
1343 * Note: it might seem that we should use mktime() for this, but bitter
1344 * experience teaches otherwise. This code is much faster than most versions
1345 * of mktime(), anyway.
1348 DetermineTimeZoneOffset(struct pg_tm * tm, pg_tz *tzp)
1358 long int before_gmtoff,
1364 if (tzp == session_timezone && HasCTZSet)
1366 tm->tm_isdst = 0; /* for lack of a better idea */
1371 * First, generate the pg_time_t value corresponding to the given
1372 * y/m/d/h/m/s taken as GMT time. If this overflows, punt and decide the
1373 * timezone is GMT. (We only need to worry about overflow on machines
1374 * where pg_time_t is 32 bits.)
1376 if (!IS_VALID_JULIAN(tm->tm_year, tm->tm_mon, tm->tm_mday))
1378 date = date2j(tm->tm_year, tm->tm_mon, tm->tm_mday) - UNIX_EPOCH_JDATE;
1380 day = ((pg_time_t) date) * SECS_PER_DAY;
1381 if (day / SECS_PER_DAY != date)
1383 sec = tm->tm_sec + (tm->tm_min + tm->tm_hour * MINS_PER_HOUR) * SECS_PER_MINUTE;
1385 /* since sec >= 0, overflow could only be from +day to -mytime */
1386 if (mytime < 0 && day > 0)
1390 * Find the DST time boundary just before or following the target time. We
1391 * assume that all zones have GMT offsets less than 24 hours, and that DST
1392 * boundaries can't be closer together than 48 hours, so backing up 24
1393 * hours and finding the "next" boundary will work.
1395 prevtime = mytime - SECS_PER_DAY;
1396 if (mytime < 0 && prevtime > 0)
1399 res = pg_next_dst_boundary(&prevtime,
1400 &before_gmtoff, &before_isdst,
1402 &after_gmtoff, &after_isdst,
1405 goto overflow; /* failure? */
1409 /* Non-DST zone, life is simple */
1410 tm->tm_isdst = before_isdst;
1411 return -(int) before_gmtoff;
1415 * Form the candidate pg_time_t values with local-time adjustment
1417 beforetime = mytime - before_gmtoff;
1418 if ((before_gmtoff > 0 &&
1419 mytime < 0 && beforetime > 0) ||
1420 (before_gmtoff <= 0 &&
1421 mytime > 0 && beforetime < 0))
1423 aftertime = mytime - after_gmtoff;
1424 if ((after_gmtoff > 0 &&
1425 mytime < 0 && aftertime > 0) ||
1426 (after_gmtoff <= 0 &&
1427 mytime > 0 && aftertime < 0))
1431 * If both before or both after the boundary time, we know what to do
1433 if (beforetime <= boundary && aftertime < boundary)
1435 tm->tm_isdst = before_isdst;
1436 return -(int) before_gmtoff;
1438 if (beforetime > boundary && aftertime >= boundary)
1440 tm->tm_isdst = after_isdst;
1441 return -(int) after_gmtoff;
1445 * It's an invalid or ambiguous time due to timezone transition. Prefer
1446 * the standard-time interpretation.
1448 if (after_isdst == 0)
1450 tm->tm_isdst = after_isdst;
1451 return -(int) after_gmtoff;
1453 tm->tm_isdst = before_isdst;
1454 return -(int) before_gmtoff;
1457 /* Given date is out of range, so assume UTC */
1464 * Interpret parsed string as time fields only.
1465 * Returns 0 if successful, DTERR code if bogus input detected.
1467 * Note that support for time zone is here for
1468 * SQL92 TIME WITH TIME ZONE, but it reveals
1469 * bogosity with SQL92 date/time standards, since
1470 * we must infer a time zone from current time.
1471 * - thomas 2000-03-10
1472 * Allow specifying date to get a better time zone,
1473 * if time zones are allowed. - thomas 2001-12-26
1476 DecodeTimeOnly(char **field, int *ftype, int nf,
1477 int *dtype, struct pg_tm * tm, fsec_t *fsec, int *tzp)
1482 int ptype = 0; /* "prefix type" for ISO h04mm05s06 format */
1486 bool is2digits = FALSE;
1488 pg_tz *namedTz = NULL;
1495 /* don't know daylight savings time status apriori */
1501 for (i = 0; i < nf; i++)
1508 * Time zone not allowed? Then should not accept dates or time
1509 * zones no matter what else!
1512 return DTERR_BAD_FORMAT;
1514 /* Under limited circumstances, we will accept a date... */
1515 if (i == 0 && nf >= 2 &&
1516 (ftype[nf - 1] == DTK_DATE || ftype[1] == DTK_TIME))
1518 dterr = DecodeDate(field[i], fmask, &tmask, tm);
1522 /* otherwise, this is a time and/or time zone */
1525 if (isdigit((unsigned char) *field[i]))
1530 * Starts with a digit but we already have a time
1531 * field? Then we are in trouble with time already...
1533 if ((fmask & DTK_TIME_M) == DTK_TIME_M)
1534 return DTERR_BAD_FORMAT;
1537 * Should not get here and fail. Sanity check only...
1539 if ((cp = strchr(field[i], '-')) == NULL)
1540 return DTERR_BAD_FORMAT;
1542 /* Get the time zone from the end of the string */
1543 dterr = DecodeTimezone(cp, tzp);
1549 * Then read the rest of the field as a concatenated
1552 dterr = DecodeNumberField(strlen(field[i]), field[i],
1553 (fmask | DTK_DATE_M),
1564 namedTz = pg_tzset(field[i]);
1568 * We should return an error code instead of
1569 * ereport'ing directly, but then there is no way
1570 * to report the bad time zone name.
1573 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1574 errmsg("time zone \"%s\" not recognized",
1577 /* we'll apply the zone setting below */
1585 dterr = DecodeTime(field[i], (fmask | DTK_DATE_M),
1596 return DTERR_BAD_FORMAT;
1598 dterr = DecodeTimezone(field[i], &tz);
1609 * Was this an "ISO time" with embedded field labels? An
1610 * example is "h04m05s06" - thomas 2001-02-04
1617 /* Only accept a date under limited circumstances */
1625 return DTERR_BAD_FORMAT;
1631 val = strtol(field[i], &cp, 10);
1632 if (errno == ERANGE)
1633 return DTERR_FIELD_OVERFLOW;
1636 * only a few kinds are allowed to have an embedded
1647 return DTERR_BAD_FORMAT;
1650 else if (*cp != '\0')
1651 return DTERR_BAD_FORMAT;
1657 tmask = DTK_M(YEAR);
1663 * already have a month and hour? then assume
1666 if ((fmask & DTK_M(MONTH)) != 0 &&
1667 (fmask & DTK_M(HOUR)) != 0)
1670 tmask = DTK_M(MINUTE);
1675 tmask = DTK_M(MONTH);
1686 tmask = DTK_M(HOUR);
1691 tmask = DTK_M(MINUTE);
1696 tmask = DTK_M(SECOND);
1701 frac = strtod(cp, &cp);
1703 return DTERR_BAD_FORMAT;
1704 #ifdef HAVE_INT64_TIMESTAMP
1705 *fsec = rint(frac * 1000000);
1709 tmask = DTK_ALL_SECS_M;
1715 dterr = DecodeTimezone(field[i], tzp);
1722 * previous field was a label for "julian date"?
1725 j2date(val, &tm->tm_year, &tm->tm_mon, &tm->tm_mday);
1730 time = strtod(cp, &cp);
1732 return DTERR_BAD_FORMAT;
1734 tmask |= DTK_TIME_M;
1735 #ifdef HAVE_INT64_TIMESTAMP
1736 dt2time(time * USECS_PER_DAY,
1737 &tm->tm_hour, &tm->tm_min, &tm->tm_sec, fsec);
1739 dt2time(time * SECS_PER_DAY,
1740 &tm->tm_hour, &tm->tm_min, &tm->tm_sec, fsec);
1746 /* previous field was "t" for ISO time */
1747 dterr = DecodeNumberField(strlen(field[i]), field[i],
1748 (fmask | DTK_DATE_M),
1755 if (tmask != DTK_TIME_M)
1756 return DTERR_BAD_FORMAT;
1760 return DTERR_BAD_FORMAT;
1772 flen = strlen(field[i]);
1773 cp = strchr(field[i], '.');
1775 /* Embedded decimal? */
1779 * Under limited circumstances, we will accept a
1782 if (i == 0 && nf >= 2 && ftype[nf - 1] == DTK_DATE)
1784 dterr = DecodeDate(field[i], fmask, &tmask, tm);
1788 /* embedded decimal and several digits before? */
1789 else if (flen - strlen(cp) > 2)
1792 * Interpret as a concatenated date or time Set
1793 * the type field to allow decoding other fields
1794 * later. Example: 20011223 or 040506
1796 dterr = DecodeNumberField(flen, field[i],
1797 (fmask | DTK_DATE_M),
1805 return DTERR_BAD_FORMAT;
1809 dterr = DecodeNumberField(flen, field[i],
1810 (fmask | DTK_DATE_M),
1817 /* otherwise it is a single date/time field... */
1820 dterr = DecodeNumber(flen, field[i],
1822 (fmask | DTK_DATE_M),
1833 type = DecodeSpecial(i, field[i], &val);
1834 if (type == IGNORE_DTF)
1837 tmask = DTK_M(type);
1845 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1846 errmsg("date/time value \"current\" is no longer supported")));
1847 return DTERR_BAD_FORMAT;
1853 GetCurrentTimeUsec(tm, fsec, NULL);
1857 tmask = (DTK_TIME_M | DTK_M(TZ));
1866 return DTERR_BAD_FORMAT;
1874 * daylight savings time modifier (solves "MET DST"
1877 tmask |= DTK_M(DTZ);
1880 return DTERR_BAD_FORMAT;
1881 *tzp += val * MINS_PER_HOUR;
1887 * set mask for TZ here _or_ check for DTZ later when
1888 * getting default timezone
1893 return DTERR_BAD_FORMAT;
1894 *tzp = val * MINS_PER_HOUR;
1901 return DTERR_BAD_FORMAT;
1902 *tzp = val * MINS_PER_HOUR;
1922 * We will need one of the following fields:
1923 * DTK_NUMBER should be hhmmss.fff
1924 * DTK_TIME should be hh:mm:ss.fff
1925 * DTK_DATE should be hhmmss-zz
1928 (ftype[i + 1] != DTK_NUMBER &&
1929 ftype[i + 1] != DTK_TIME &&
1930 ftype[i + 1] != DTK_DATE))
1931 return DTERR_BAD_FORMAT;
1939 * Before giving up and declaring error, check to see
1940 * if it is an all-alpha timezone name.
1942 namedTz = pg_tzset(field[i]);
1944 return DTERR_BAD_FORMAT;
1945 /* we'll apply the zone setting below */
1950 return DTERR_BAD_FORMAT;
1955 return DTERR_BAD_FORMAT;
1959 return DTERR_BAD_FORMAT;
1963 if (mer != HR24 && tm->tm_hour > 12)
1964 return DTERR_FIELD_OVERFLOW;
1965 if (mer == AM && tm->tm_hour == 12)
1967 else if (mer == PM && tm->tm_hour != 12)
1970 if (tm->tm_hour < 0 || tm->tm_min < 0 || tm->tm_min > 59 ||
1971 tm->tm_sec < 0 || tm->tm_sec > 60 || tm->tm_hour > 24 ||
1972 /* test for > 24:00:00 */
1973 #ifdef HAVE_INT64_TIMESTAMP
1974 (tm->tm_hour == 24 && (tm->tm_min > 0 || tm->tm_sec > 0 ||
1975 *fsec > INT64CONST(0))) ||
1976 *fsec < INT64CONST(0) || *fsec >= USECS_PER_SEC
1978 (tm->tm_hour == 24 && (tm->tm_min > 0 || tm->tm_sec > 0 ||
1980 *fsec < 0 || *fsec >= 1
1983 return DTERR_FIELD_OVERFLOW;
1985 if ((fmask & DTK_TIME_M) != DTK_TIME_M)
1986 return DTERR_BAD_FORMAT;
1989 * If we had a full timezone spec, compute the offset (we could not do it
1990 * before, because we may need the date to resolve DST status).
1992 if (namedTz != NULL)
1996 /* daylight savings time modifier disallowed with full TZ */
1997 if (fmask & DTK_M(DTZMOD))
1998 return DTERR_BAD_FORMAT;
2000 /* if non-DST zone, we do not need to know the date */
2001 if (pg_get_timezone_offset(namedTz, &gmtoff))
2003 *tzp = -(int) gmtoff;
2007 /* a date has to be specified */
2008 if ((fmask & DTK_DATE_M) != DTK_DATE_M)
2009 return DTERR_BAD_FORMAT;
2010 *tzp = DetermineTimeZoneOffset(tm, namedTz);
2014 /* timezone not specified? then find local timezone if possible */
2015 if (tzp != NULL && !(fmask & DTK_M(TZ)))
2021 * daylight savings time modifier but no standard timezone? then error
2023 if (fmask & DTK_M(DTZMOD))
2024 return DTERR_BAD_FORMAT;
2026 if ((fmask & DTK_DATE_M) == 0)
2027 GetCurrentDateTime(tmp);
2030 tmp->tm_year = tm->tm_year;
2031 tmp->tm_mon = tm->tm_mon;
2032 tmp->tm_mday = tm->tm_mday;
2034 tmp->tm_hour = tm->tm_hour;
2035 tmp->tm_min = tm->tm_min;
2036 tmp->tm_sec = tm->tm_sec;
2037 *tzp = DetermineTimeZoneOffset(tmp, session_timezone);
2038 tm->tm_isdst = tmp->tm_isdst;
2045 * Decode date string which includes delimiters.
2046 * Return 0 if okay, a DTERR code if not.
2048 * Insist on a complete set of fields.
2051 DecodeDate(char *str, int fmask, int *tmask, struct pg_tm * tm)
2058 bool haveTextMonth = FALSE;
2060 bool is2digits = FALSE;
2064 char *field[MAXDATEFIELDS];
2066 /* parse this string... */
2067 while (*str != '\0' && nf < MAXDATEFIELDS)
2069 /* skip field separators */
2070 while (!isalnum((unsigned char) *str))
2074 if (isdigit((unsigned char) *str))
2076 while (isdigit((unsigned char) *str))
2079 else if (isalpha((unsigned char) *str))
2081 while (isalpha((unsigned char) *str))
2085 /* Just get rid of any non-digit, non-alpha characters... */
2092 /* don't allow too many fields */
2094 return DTERR_BAD_FORMAT;
2099 /* look first for text fields, since that will be unambiguous month */
2100 for (i = 0; i < nf; i++)
2102 if (isalpha((unsigned char) *field[i]))
2104 type = DecodeSpecial(i, field[i], &val);
2105 if (type == IGNORE_DTF)
2108 dmask = DTK_M(type);
2113 haveTextMonth = TRUE;
2121 return DTERR_BAD_FORMAT;
2124 return DTERR_BAD_FORMAT;
2129 /* mark this field as being completed */
2134 /* now pick up remaining numeric fields */
2135 for (i = 0; i < nf; i++)
2137 if (field[i] == NULL)
2140 if ((len = strlen(field[i])) <= 0)
2141 return DTERR_BAD_FORMAT;
2143 dterr = DecodeNumber(len, field[i], haveTextMonth, fmask,
2150 return DTERR_BAD_FORMAT;
2156 if ((fmask & ~(DTK_M(DOY) | DTK_M(TZ))) != DTK_DATE_M)
2157 return DTERR_BAD_FORMAT;
2159 /* there is no year zero in AD/BC notation; i.e. "1 BC" == year 0 */
2162 if (tm->tm_year > 0)
2163 tm->tm_year = -(tm->tm_year - 1);
2166 (errcode(ERRCODE_INVALID_DATETIME_FORMAT),
2167 errmsg("inconsistent use of year %04d and \"BC\"",
2172 if (tm->tm_year < 70)
2173 tm->tm_year += 2000;
2174 else if (tm->tm_year < 100)
2175 tm->tm_year += 1900;
2178 /* now that we have correct year, decode DOY */
2179 if (fmask & DTK_M(DOY))
2181 j2date(date2j(tm->tm_year, 1, 1) + tm->tm_yday - 1,
2182 &tm->tm_year, &tm->tm_mon, &tm->tm_mday);
2185 /* check for valid month */
2186 if (tm->tm_mon < 1 || tm->tm_mon > MONTHS_PER_YEAR)
2187 return DTERR_MD_FIELD_OVERFLOW;
2189 /* check for valid day */
2190 if (tm->tm_mday < 1 || tm->tm_mday > 31)
2191 return DTERR_MD_FIELD_OVERFLOW;
2193 /* We don't want to hint about DateStyle for Feb 29 */
2194 if (tm->tm_mday > day_tab[isleap(tm->tm_year)][tm->tm_mon - 1])
2195 return DTERR_FIELD_OVERFLOW;
2202 * Decode time string which includes delimiters.
2203 * Return 0 if okay, a DTERR code if not.
2205 * Only check the lower limit on hours, since this same code can be
2206 * used to represent time spans.
2209 DecodeTime(char *str, int fmask, int *tmask, struct pg_tm * tm, fsec_t *fsec)
2213 *tmask = DTK_TIME_M;
2216 tm->tm_hour = strtol(str, &cp, 10);
2217 if (errno == ERANGE)
2218 return DTERR_FIELD_OVERFLOW;
2220 return DTERR_BAD_FORMAT;
2223 tm->tm_min = strtol(str, &cp, 10);
2224 if (errno == ERANGE)
2225 return DTERR_FIELD_OVERFLOW;
2231 else if (*cp != ':')
2232 return DTERR_BAD_FORMAT;
2237 tm->tm_sec = strtol(str, &cp, 10);
2238 if (errno == ERANGE)
2239 return DTERR_FIELD_OVERFLOW;
2242 else if (*cp == '.')
2247 frac = strtod(str, &cp);
2249 return DTERR_BAD_FORMAT;
2250 #ifdef HAVE_INT64_TIMESTAMP
2251 *fsec = rint(frac * 1000000);
2257 return DTERR_BAD_FORMAT;
2260 /* do a sanity check */
2261 #ifdef HAVE_INT64_TIMESTAMP
2262 if (tm->tm_hour < 0 || tm->tm_min < 0 || tm->tm_min > 59 ||
2263 tm->tm_sec < 0 || tm->tm_sec > 60 || *fsec < INT64CONST(0) ||
2264 *fsec >= USECS_PER_SEC)
2265 return DTERR_FIELD_OVERFLOW;
2267 if (tm->tm_hour < 0 || tm->tm_min < 0 || tm->tm_min > 59 ||
2268 tm->tm_sec < 0 || tm->tm_sec > 60 || *fsec < 0 || *fsec >= 1)
2269 return DTERR_FIELD_OVERFLOW;
2277 * Interpret plain numeric field as a date value in context.
2278 * Return 0 if okay, a DTERR code if not.
2281 DecodeNumber(int flen, char *str, bool haveTextMonth, int fmask,
2282 int *tmask, struct pg_tm * tm, fsec_t *fsec, bool *is2digits)
2291 val = strtol(str, &cp, 10);
2292 if (errno == ERANGE)
2293 return DTERR_FIELD_OVERFLOW;
2295 return DTERR_BAD_FORMAT;
2302 * More than two digits before decimal point? Then could be a date or
2303 * a run-together time: 2001.360 20011225 040506.789
2307 dterr = DecodeNumberField(flen, str,
2308 (fmask | DTK_DATE_M),
2316 frac = strtod(cp, &cp);
2318 return DTERR_BAD_FORMAT;
2319 #ifdef HAVE_INT64_TIMESTAMP
2320 *fsec = rint(frac * 1000000);
2325 else if (*cp != '\0')
2326 return DTERR_BAD_FORMAT;
2328 /* Special case for day of year */
2329 if (flen == 3 && (fmask & DTK_DATE_M) == DTK_M(YEAR) && val >= 1 &&
2332 *tmask = (DTK_M(DOY) | DTK_M(MONTH) | DTK_M(DAY));
2334 /* tm_mon and tm_mday can't actually be set yet ... */
2338 /* Switch based on what we have so far */
2339 switch (fmask & DTK_DATE_M)
2344 * Nothing so far; make a decision about what we think the input
2345 * is. There used to be lots of heuristics here, but the
2346 * consensus now is to be paranoid. It *must* be either
2347 * YYYY-MM-DD (with a more-than-two-digit year field), or the
2348 * field order defined by DateOrder.
2350 if (flen >= 3 || DateOrder == DATEORDER_YMD)
2352 *tmask = DTK_M(YEAR);
2355 else if (DateOrder == DATEORDER_DMY)
2357 *tmask = DTK_M(DAY);
2362 *tmask = DTK_M(MONTH);
2368 /* Must be at second field of YY-MM-DD */
2369 *tmask = DTK_M(MONTH);
2373 case (DTK_M(MONTH)):
2377 * We are at the first numeric field of a date that included a
2378 * textual month name. We want to support the variants
2379 * MON-DD-YYYY, DD-MON-YYYY, and YYYY-MON-DD as unambiguous
2380 * inputs. We will also accept MON-DD-YY or DD-MON-YY in
2381 * either DMY or MDY modes, as well as YY-MON-DD in YMD mode.
2383 if (flen >= 3 || DateOrder == DATEORDER_YMD)
2385 *tmask = DTK_M(YEAR);
2390 *tmask = DTK_M(DAY);
2396 /* Must be at second field of MM-DD-YY */
2397 *tmask = DTK_M(DAY);
2402 case (DTK_M(YEAR) | DTK_M(MONTH)):
2405 /* Need to accept DD-MON-YYYY even in YMD mode */
2406 if (flen >= 3 && *is2digits)
2408 /* Guess that first numeric field is day was wrong */
2409 *tmask = DTK_M(DAY); /* YEAR is already set */
2410 tm->tm_mday = tm->tm_year;
2416 *tmask = DTK_M(DAY);
2422 /* Must be at third field of YY-MM-DD */
2423 *tmask = DTK_M(DAY);
2429 /* Must be at second field of DD-MM-YY */
2430 *tmask = DTK_M(MONTH);
2434 case (DTK_M(MONTH) | DTK_M(DAY)):
2435 /* Must be at third field of DD-MM-YY or MM-DD-YY */
2436 *tmask = DTK_M(YEAR);
2440 case (DTK_M(YEAR) | DTK_M(MONTH) | DTK_M(DAY)):
2441 /* we have all the date, so it must be a time field */
2442 dterr = DecodeNumberField(flen, str, fmask,
2450 /* Anything else is bogus input */
2451 return DTERR_BAD_FORMAT;
2455 * When processing a year field, mark it for adjustment if it's only one
2458 if (*tmask == DTK_M(YEAR))
2459 *is2digits = (flen <= 2);
2465 /* DecodeNumberField()
2466 * Interpret numeric string as a concatenated date or time field.
2467 * Return a DTK token (>= 0) if successful, a DTERR code (< 0) if not.
2469 * Use the context of previously decoded fields to help with
2470 * the interpretation.
2473 DecodeNumberField(int len, char *str, int fmask,
2474 int *tmask, struct pg_tm * tm, fsec_t *fsec, bool *is2digits)
2479 * Have a decimal point? Then this is a date or something with a seconds
2482 if ((cp = strchr(str, '.')) != NULL)
2486 frac = strtod(cp, NULL);
2487 #ifdef HAVE_INT64_TIMESTAMP
2488 *fsec = rint(frac * 1000000);
2495 /* No decimal point and no complete date yet? */
2496 else if ((fmask & DTK_DATE_M) != DTK_DATE_M)
2501 *tmask = DTK_DATE_M;
2503 tm->tm_mday = atoi(str + 6);
2505 tm->tm_mon = atoi(str + 4);
2507 tm->tm_year = atoi(str + 0);
2514 *tmask = DTK_DATE_M;
2515 tm->tm_mday = atoi(str + 4);
2517 tm->tm_mon = atoi(str + 2);
2519 tm->tm_year = atoi(str + 0);
2526 /* not all time fields are specified? */
2527 if ((fmask & DTK_TIME_M) != DTK_TIME_M)
2532 *tmask = DTK_TIME_M;
2533 tm->tm_sec = atoi(str + 4);
2535 tm->tm_min = atoi(str + 2);
2537 tm->tm_hour = atoi(str + 0);
2544 *tmask = DTK_TIME_M;
2546 tm->tm_min = atoi(str + 2);
2548 tm->tm_hour = atoi(str + 0);
2554 return DTERR_BAD_FORMAT;
2559 * Interpret string as a numeric timezone.
2561 * Return 0 if okay (and set *tzp), a DTERR code if not okay.
2563 * NB: this must *not* ereport on failure; see commands/variable.c.
2565 * Note: we allow timezone offsets up to 13:59. There are places that
2566 * use +1300 summer time.
2569 DecodeTimezone(char *str, int *tzp)
2577 /* leading character must be "+" or "-" */
2578 if (*str != '+' && *str != '-')
2579 return DTERR_BAD_FORMAT;
2582 hr = strtol(str + 1, &cp, 10);
2583 if (errno == ERANGE)
2584 return DTERR_TZDISP_OVERFLOW;
2586 /* explicit delimiter? */
2590 min = strtol(cp + 1, &cp, 10);
2591 if (errno == ERANGE)
2592 return DTERR_TZDISP_OVERFLOW;
2596 sec = strtol(cp + 1, &cp, 10);
2597 if (errno == ERANGE)
2598 return DTERR_TZDISP_OVERFLOW;
2601 /* otherwise, might have run things together... */
2602 else if (*cp == '\0' && strlen(str) > 3)
2606 /* we could, but don't, support a run-together hhmmss format */
2611 if (hr < 0 || hr > 14)
2612 return DTERR_TZDISP_OVERFLOW;
2613 if (min < 0 || min >= 60)
2614 return DTERR_TZDISP_OVERFLOW;
2615 if (sec < 0 || sec >= 60)
2616 return DTERR_TZDISP_OVERFLOW;
2618 tz = (hr * MINS_PER_HOUR + min) * SECS_PER_MINUTE + sec;
2625 return DTERR_BAD_FORMAT;
2631 * Decode text string using lookup table.
2633 * Implement a cache lookup since it is likely that dates
2634 * will be related in format.
2636 * NB: this must *not* ereport on failure;
2637 * see commands/variable.c.
2640 DecodeSpecial(int field, char *lowtoken, int *val)
2645 tp = datecache[field];
2646 if (tp == NULL || strncmp(lowtoken, tp->token, TOKMAXLEN) != 0)
2648 tp = datebsearch(lowtoken, timezonetktbl, sztimezonetktbl);
2650 tp = datebsearch(lowtoken, datetktbl, szdatetktbl);
2654 type = UNKNOWN_FIELD;
2659 datecache[field] = tp;
2680 * Interpret previously parsed fields for general time interval.
2681 * Returns 0 if successful, DTERR code if bogus input detected.
2683 * Allow "date" field DTK_DATE since this could be just
2684 * an unsigned floating point number. - thomas 1997-11-16
2686 * Allow ISO-style time span, with implicit units on number of days
2687 * preceding an hh:mm:ss field. - thomas 1998-04-30
2690 DecodeInterval(char **field, int *ftype, int nf, int *dtype, struct pg_tm * tm, fsec_t *fsec)
2692 bool is_before = FALSE;
2713 /* read through list backwards to pick up units before values */
2714 for (i = nf - 1; i >= 0; i--)
2719 dterr = DecodeTime(field[i], fmask, &tmask, tm, fsec);
2728 * Timezone is a token with a leading sign character and
2729 * otherwise the same as a non-signed time field
2731 Assert(*field[i] == '-' || *field[i] == '+');
2734 * A single signed number ends up here, but will be rejected
2735 * by DecodeTime(). So, work this out to drop through to
2736 * DTK_NUMBER, which *can* tolerate this.
2739 while (*cp != '\0' && *cp != ':' && *cp != '.')
2742 DecodeTime(field[i] + 1, fmask, &tmask, tm, fsec) == 0)
2744 if (*field[i] == '-')
2746 /* flip the sign on all fields */
2747 tm->tm_hour = -tm->tm_hour;
2748 tm->tm_min = -tm->tm_min;
2749 tm->tm_sec = -tm->tm_sec;
2754 * Set the next type to be a day, if units are not
2755 * specified. This handles the case of '1 +02:03' since we
2756 * are reading right to left.
2762 else if (type == IGNORE_DTF)
2767 * Got a decimal point? Then assume some sort of
2768 * seconds specification
2772 else if (*cp == '\0')
2775 * Only a signed integer? Then must assume a
2776 * timezone-like usage
2786 val = strtol(field[i], &cp, 10);
2787 if (errno == ERANGE)
2788 return DTERR_FIELD_OVERFLOW;
2790 if (type == IGNORE_DTF)
2795 fval = strtod(cp, &cp);
2797 return DTERR_BAD_FORMAT;
2799 if (*field[i] == '-')
2802 else if (*cp == '\0')
2805 return DTERR_BAD_FORMAT;
2807 tmask = 0; /* DTK_M(type); */
2812 #ifdef HAVE_INT64_TIMESTAMP
2813 *fsec += val + fval;
2815 *fsec += (val + fval) * 1e-6;
2817 tmask = DTK_M(MICROSECOND);
2821 #ifdef HAVE_INT64_TIMESTAMP
2822 *fsec += (val + fval) * 1000;
2824 *fsec += (val + fval) * 1e-3;
2826 tmask = DTK_M(MILLISECOND);
2831 #ifdef HAVE_INT64_TIMESTAMP
2832 *fsec += fval * 1000000;
2838 * If any subseconds were specified, consider this
2839 * microsecond and millisecond input as well.
2842 tmask = DTK_M(SECOND);
2844 tmask = DTK_ALL_SECS_M;
2853 fval *= SECS_PER_MINUTE;
2856 #ifdef HAVE_INT64_TIMESTAMP
2857 *fsec += (fval - sec) * 1000000;
2859 *fsec += fval - sec;
2862 tmask = DTK_M(MINUTE);
2871 fval *= SECS_PER_HOUR;
2874 #ifdef HAVE_INT64_TIMESTAMP
2875 *fsec += (fval - sec) * 1000000;
2877 *fsec += fval - sec;
2880 tmask = DTK_M(HOUR);
2889 fval *= SECS_PER_DAY;
2892 #ifdef HAVE_INT64_TIMESTAMP
2893 *fsec += (fval - sec) * 1000000;
2895 *fsec += fval - sec;
2898 tmask = (fmask & DTK_M(DAY)) ? 0 : DTK_M(DAY);
2902 tm->tm_mday += val * 7;
2908 extra_days = (int32) fval;
2909 tm->tm_mday += extra_days;
2915 fval *= SECS_PER_DAY;
2918 #ifdef HAVE_INT64_TIMESTAMP
2919 *fsec += (fval - sec) * 1000000;
2921 *fsec += fval - sec;
2925 tmask = (fmask & DTK_M(DAY)) ? 0 : DTK_M(DAY);
2934 fval *= DAYS_PER_MONTH;
2942 fval *= SECS_PER_DAY;
2945 #ifdef HAVE_INT64_TIMESTAMP
2946 *fsec += (fval - sec) * 1000000;
2948 *fsec += fval - sec;
2952 tmask = DTK_M(MONTH);
2958 tm->tm_mon += fval * MONTHS_PER_YEAR;
2959 tmask = (fmask & DTK_M(YEAR)) ? 0 : DTK_M(YEAR);
2963 tm->tm_year += val * 10;
2965 tm->tm_mon += fval * MONTHS_PER_YEAR * 10;
2966 tmask = (fmask & DTK_M(YEAR)) ? 0 : DTK_M(YEAR);
2970 tm->tm_year += val * 100;
2972 tm->tm_mon += fval * MONTHS_PER_YEAR * 100;
2973 tmask = (fmask & DTK_M(YEAR)) ? 0 : DTK_M(YEAR);
2976 case DTK_MILLENNIUM:
2977 tm->tm_year += val * 1000;
2979 tm->tm_mon += fval * MONTHS_PER_YEAR * 1000;
2980 tmask = (fmask & DTK_M(YEAR)) ? 0 : DTK_M(YEAR);
2984 return DTERR_BAD_FORMAT;
2990 type = DecodeUnits(i, field[i], &val);
2991 if (type == IGNORE_DTF)
2994 tmask = 0; /* DTK_M(type); */
3007 tmask = (DTK_DATE_M || DTK_TIME_M);
3012 return DTERR_BAD_FORMAT;
3017 return DTERR_BAD_FORMAT;
3021 return DTERR_BAD_FORMAT;
3029 #ifdef HAVE_INT64_TIMESTAMP
3030 sec = *fsec / USECS_PER_SEC;
3031 *fsec -= sec * USECS_PER_SEC;
3033 TMODULO(*fsec, sec, 1.0);
3041 tm->tm_sec = -tm->tm_sec;
3042 tm->tm_min = -tm->tm_min;
3043 tm->tm_hour = -tm->tm_hour;
3044 tm->tm_mday = -tm->tm_mday;
3045 tm->tm_mon = -tm->tm_mon;
3046 tm->tm_year = -tm->tm_year;
3049 /* ensure that at least one time field has been found */
3051 return DTERR_BAD_FORMAT;
3058 * Decode text string using lookup table.
3059 * This routine supports time interval decoding
3060 * (hence, it need not recognize timezone names).
3063 DecodeUnits(int field, char *lowtoken, int *val)
3068 tp = deltacache[field];
3069 if (tp == NULL || strncmp(lowtoken, tp->token, TOKMAXLEN) != 0)
3071 tp = datebsearch(lowtoken, deltatktbl, szdeltatktbl);
3075 type = UNKNOWN_FIELD;
3080 deltacache[field] = tp;
3082 if (type == TZ || type == DTZ)
3089 } /* DecodeUnits() */
3092 * Report an error detected by one of the datetime input processing routines.
3094 * dterr is the error code, str is the original input string, datatype is
3095 * the name of the datatype we were trying to accept.
3097 * Note: it might seem useless to distinguish DTERR_INTERVAL_OVERFLOW and
3098 * DTERR_TZDISP_OVERFLOW from DTERR_FIELD_OVERFLOW, but SQL99 mandates three
3099 * separate SQLSTATE codes, so ...
3102 DateTimeParseError(int dterr, const char *str, const char *datatype)
3106 case DTERR_FIELD_OVERFLOW:
3108 (errcode(ERRCODE_DATETIME_FIELD_OVERFLOW),
3109 errmsg("date/time field value out of range: \"%s\"",
3112 case DTERR_MD_FIELD_OVERFLOW:
3113 /* <nanny>same as above, but add hint about DateStyle</nanny> */
3115 (errcode(ERRCODE_DATETIME_FIELD_OVERFLOW),
3116 errmsg("date/time field value out of range: \"%s\"",
3118 errhint("Perhaps you need a different \"datestyle\" setting.")));
3120 case DTERR_INTERVAL_OVERFLOW:
3122 (errcode(ERRCODE_INTERVAL_FIELD_OVERFLOW),
3123 errmsg("interval field value out of range: \"%s\"",
3126 case DTERR_TZDISP_OVERFLOW:
3128 (errcode(ERRCODE_INVALID_TIME_ZONE_DISPLACEMENT_VALUE),
3129 errmsg("time zone displacement out of range: \"%s\"",
3132 case DTERR_BAD_FORMAT:
3135 (errcode(ERRCODE_INVALID_DATETIME_FORMAT),
3136 errmsg("invalid input syntax for type %s: \"%s\"",
3143 * Binary search -- from Knuth (6.2.1) Algorithm B. Special case like this
3144 * is WAY faster than the generic bsearch().
3146 static const datetkn *
3147 datebsearch(const char *key, const datetkn *base, int nel)
3149 const datetkn *last = base + nel - 1,
3153 while (last >= base)
3155 position = base + ((last - base) >> 1);
3156 result = key[0] - position->token[0];
3159 result = strncmp(key, position->token, TOKMAXLEN);
3164 last = position - 1;
3166 base = position + 1;
3172 * Append representation of a numeric timezone offset to str.
3175 EncodeTimezone(char *str, int tz, int style)
3182 min = sec / SECS_PER_MINUTE;
3183 sec -= min * SECS_PER_MINUTE;
3184 hour = min / MINS_PER_HOUR;
3185 min -= hour * MINS_PER_HOUR;
3188 /* TZ is negated compared to sign we wish to display ... */
3189 *str++ = (tz <= 0 ? '+' : '-');
3192 sprintf(str, "%02d:%02d:%02d", hour, min, sec);
3193 else if (min != 0 || style == USE_XSD_DATES)
3194 sprintf(str, "%02d:%02d", hour, min);
3196 sprintf(str, "%02d", hour);
3200 * Encode date as local time.
3203 EncodeDateOnly(struct pg_tm * tm, int style, char *str)
3205 if (tm->tm_mon < 1 || tm->tm_mon > MONTHS_PER_YEAR)
3212 /* compatible with ISO date formats */
3213 if (tm->tm_year > 0)
3214 sprintf(str, "%04d-%02d-%02d",
3215 tm->tm_year, tm->tm_mon, tm->tm_mday);
3217 sprintf(str, "%04d-%02d-%02d %s",
3218 -(tm->tm_year - 1), tm->tm_mon, tm->tm_mday, "BC");
3222 /* compatible with Oracle/Ingres date formats */
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");
3233 case USE_GERMAN_DATES:
3234 /* German-style date format */
3235 sprintf(str, "%02d.%02d", tm->tm_mday, tm->tm_mon);
3236 if (tm->tm_year > 0)
3237 sprintf(str + 5, ".%04d", tm->tm_year);
3239 sprintf(str + 5, ".%04d %s", -(tm->tm_year - 1), "BC");
3242 case USE_POSTGRES_DATES:
3244 /* traditional date-only style for Postgres */
3245 if (DateOrder == DATEORDER_DMY)
3246 sprintf(str, "%02d-%02d", tm->tm_mday, tm->tm_mon);
3248 sprintf(str, "%02d-%02d", tm->tm_mon, tm->tm_mday);
3249 if (tm->tm_year > 0)
3250 sprintf(str + 5, "-%04d", tm->tm_year);
3252 sprintf(str + 5, "-%04d %s", -(tm->tm_year - 1), "BC");
3257 } /* EncodeDateOnly() */
3261 * Encode time fields only.
3264 EncodeTimeOnly(struct pg_tm * tm, fsec_t fsec, int *tzp, int style, char *str)
3266 if (tm->tm_hour < 0 || tm->tm_hour > HOURS_PER_DAY)
3269 sprintf(str, "%02d:%02d", tm->tm_hour, tm->tm_min);
3272 * Print fractional seconds if any. The fractional field widths here
3273 * should be equal to the larger of MAX_TIME_PRECISION and
3274 * MAX_TIMESTAMP_PRECISION.
3278 #ifdef HAVE_INT64_TIMESTAMP
3279 sprintf(str + strlen(str), ":%02d.%06d", tm->tm_sec, fsec);
3281 sprintf(str + strlen(str), ":%013.10f", tm->tm_sec + fsec);
3283 TrimTrailingZeros(str);
3286 sprintf(str + strlen(str), ":%02d", tm->tm_sec);
3289 EncodeTimezone(str, *tzp, style);
3292 } /* EncodeTimeOnly() */
3296 * Encode date and time interpreted as local time.
3297 * Support several date styles:
3298 * Postgres - day mon hh:mm:ss yyyy tz
3299 * SQL - mm/dd/yyyy hh:mm:ss.ss tz
3300 * ISO - yyyy-mm-dd hh:mm:ss+/-tz
3301 * German - dd.mm.yyyy hh:mm:ss tz
3302 * XSD - yyyy-mm-ddThh:mm:ss.ss+/-tz
3303 * Variants (affects order of month and day for Postgres and SQL styles):
3305 * European - dd/mm/yyyy
3308 EncodeDateTime(struct pg_tm * tm, fsec_t fsec, int *tzp, char **tzn, int style, char *str)
3313 * Why are we checking only the month field? Change this to an assert...
3314 * if (tm->tm_mon < 1 || tm->tm_mon > MONTHS_PER_YEAR) return -1;
3316 Assert(tm->tm_mon >= 1 && tm->tm_mon <= MONTHS_PER_YEAR);
3322 /* Compatible with ISO-8601 date formats */
3324 if (style == USE_ISO_DATES)
3325 sprintf(str, "%04d-%02d-%02d %02d:%02d",
3326 (tm->tm_year > 0) ? tm->tm_year : -(tm->tm_year - 1),
3327 tm->tm_mon, tm->tm_mday, tm->tm_hour, tm->tm_min);
3329 sprintf(str, "%04d-%02d-%02dT%02d:%02d",
3330 (tm->tm_year > 0) ? tm->tm_year : -(tm->tm_year - 1),
3331 tm->tm_mon, tm->tm_mday, tm->tm_hour, tm->tm_min);
3335 * Print fractional seconds if any. The field widths here should
3336 * be at least equal to MAX_TIMESTAMP_PRECISION.
3338 * In float mode, don't print fractional seconds before 1 AD,
3339 * since it's unlikely there's any precision left ...
3341 #ifdef HAVE_INT64_TIMESTAMP
3344 sprintf(str + strlen(str), ":%02d.%06d", tm->tm_sec, fsec);
3345 TrimTrailingZeros(str);
3348 if (fsec != 0 && tm->tm_year > 0)
3350 sprintf(str + strlen(str), ":%09.6f", tm->tm_sec + fsec);
3351 TrimTrailingZeros(str);
3355 sprintf(str + strlen(str), ":%02d", tm->tm_sec);
3358 * tzp == NULL indicates that we don't want *any* time zone info
3359 * in the output string. *tzn != NULL indicates that we have alpha
3360 * time zone info available. tm_isdst != -1 indicates that we have
3361 * a valid time zone translation.
3363 if (tzp != NULL && tm->tm_isdst >= 0)
3364 EncodeTimezone(str, *tzp, style);
3366 if (tm->tm_year <= 0)
3367 sprintf(str + strlen(str), " BC");
3371 /* Compatible with Oracle/Ingres date formats */
3373 if (DateOrder == DATEORDER_DMY)
3374 sprintf(str, "%02d/%02d", tm->tm_mday, tm->tm_mon);
3376 sprintf(str, "%02d/%02d", tm->tm_mon, tm->tm_mday);
3378 sprintf(str + 5, "/%04d %02d:%02d",
3379 (tm->tm_year > 0) ? tm->tm_year : -(tm->tm_year - 1),
3380 tm->tm_hour, tm->tm_min);
3383 * Print fractional seconds if any. The field widths here should
3384 * be at least equal to MAX_TIMESTAMP_PRECISION.
3386 * In float mode, don't print fractional seconds before 1 AD,
3387 * since it's unlikely there's any precision left ...
3389 #ifdef HAVE_INT64_TIMESTAMP
3392 sprintf(str + strlen(str), ":%02d.%06d", tm->tm_sec, fsec);
3393 TrimTrailingZeros(str);
3396 if (fsec != 0 && tm->tm_year > 0)
3398 sprintf(str + strlen(str), ":%09.6f", tm->tm_sec + fsec);
3399 TrimTrailingZeros(str);
3403 sprintf(str + strlen(str), ":%02d", tm->tm_sec);
3405 if (tzp != NULL && tm->tm_isdst >= 0)
3408 sprintf(str + strlen(str), " %.*s", MAXTZLEN, *tzn);
3410 EncodeTimezone(str, *tzp, style);
3413 if (tm->tm_year <= 0)
3414 sprintf(str + strlen(str), " BC");
3417 case USE_GERMAN_DATES:
3418 /* German variant on European style */
3420 sprintf(str, "%02d.%02d", tm->tm_mday, tm->tm_mon);
3422 sprintf(str + 5, ".%04d %02d:%02d",
3423 (tm->tm_year > 0) ? tm->tm_year : -(tm->tm_year - 1),
3424 tm->tm_hour, tm->tm_min);
3427 * Print fractional seconds if any. The field widths here should
3428 * be at least equal to MAX_TIMESTAMP_PRECISION.
3430 * In float mode, don't print fractional seconds before 1 AD,
3431 * since it's unlikely there's any precision left ...
3433 #ifdef HAVE_INT64_TIMESTAMP
3436 sprintf(str + strlen(str), ":%02d.%06d", tm->tm_sec, fsec);
3437 TrimTrailingZeros(str);
3440 if (fsec != 0 && tm->tm_year > 0)
3442 sprintf(str + strlen(str), ":%09.6f", tm->tm_sec + fsec);
3443 TrimTrailingZeros(str);
3447 sprintf(str + strlen(str), ":%02d", tm->tm_sec);
3449 if (tzp != NULL && tm->tm_isdst >= 0)
3452 sprintf(str + strlen(str), " %.*s", MAXTZLEN, *tzn);
3454 EncodeTimezone(str, *tzp, style);
3457 if (tm->tm_year <= 0)
3458 sprintf(str + strlen(str), " BC");
3461 case USE_POSTGRES_DATES:
3463 /* Backward-compatible with traditional Postgres abstime dates */
3465 day = date2j(tm->tm_year, tm->tm_mon, tm->tm_mday);
3466 tm->tm_wday = j2day(day);
3468 strncpy(str, days[tm->tm_wday], 3);
3469 strcpy(str + 3, " ");
3471 if (DateOrder == DATEORDER_DMY)
3472 sprintf(str + 4, "%02d %3s", tm->tm_mday, months[tm->tm_mon - 1]);
3474 sprintf(str + 4, "%3s %02d", months[tm->tm_mon - 1], tm->tm_mday);
3476 sprintf(str + 10, " %02d:%02d", tm->tm_hour, tm->tm_min);
3479 * Print fractional seconds if any. The field widths here should
3480 * be at least equal to MAX_TIMESTAMP_PRECISION.
3482 * In float mode, don't print fractional seconds before 1 AD,
3483 * since it's unlikely there's any precision left ...
3485 #ifdef HAVE_INT64_TIMESTAMP
3488 sprintf(str + strlen(str), ":%02d.%06d", tm->tm_sec, fsec);
3489 TrimTrailingZeros(str);
3492 if (fsec != 0 && tm->tm_year > 0)
3494 sprintf(str + strlen(str), ":%09.6f", tm->tm_sec + fsec);
3495 TrimTrailingZeros(str);
3499 sprintf(str + strlen(str), ":%02d", tm->tm_sec);
3501 sprintf(str + strlen(str), " %04d",
3502 (tm->tm_year > 0) ? tm->tm_year : -(tm->tm_year - 1));
3504 if (tzp != NULL && tm->tm_isdst >= 0)
3507 sprintf(str + strlen(str), " %.*s", MAXTZLEN, *tzn);
3511 * We have a time zone, but no string version. Use the
3512 * numeric form, but be sure to include a leading space to
3513 * avoid formatting something which would be rejected by
3514 * the date/time parser later. - thomas 2001-10-19
3516 sprintf(str + strlen(str), " ");
3517 EncodeTimezone(str, *tzp, style);
3521 if (tm->tm_year <= 0)
3522 sprintf(str + strlen(str), " BC");
3531 * Interpret time structure as a delta time and convert to string.
3533 * Support "traditional Postgres" and ISO-8601 styles.
3534 * Actually, afaik ISO does not address time interval formatting,
3535 * but this looks similar to the spec for absolute date/time.
3536 * - thomas 1998-04-30
3539 EncodeInterval(struct pg_tm * tm, fsec_t fsec, int style, char *str)
3541 bool is_before = FALSE;
3542 bool is_nonzero = FALSE;
3546 * The sign of year and month are guaranteed to match, since they are
3547 * stored internally as "month". But we'll need to check for is_before and
3548 * is_nonzero when determining the signs of hour/minute/seconds fields.
3552 /* compatible with ISO date formats */
3554 if (tm->tm_year != 0)
3556 sprintf(cp, "%d year%s",
3557 tm->tm_year, (tm->tm_year != 1) ? "s" : "");
3559 is_before = (tm->tm_year < 0);
3563 if (tm->tm_mon != 0)
3565 sprintf(cp, "%s%s%d mon%s", is_nonzero ? " " : "",
3566 (is_before && tm->tm_mon > 0) ? "+" : "",
3567 tm->tm_mon, (tm->tm_mon != 1) ? "s" : "");
3569 is_before = (tm->tm_mon < 0);
3573 if (tm->tm_mday != 0)
3575 sprintf(cp, "%s%s%d day%s", is_nonzero ? " " : "",
3576 (is_before && tm->tm_mday > 0) ? "+" : "",
3577 tm->tm_mday, (tm->tm_mday != 1) ? "s" : "");
3579 is_before = (tm->tm_mday < 0);
3583 if (!is_nonzero || tm->tm_hour != 0 || tm->tm_min != 0 ||
3584 tm->tm_sec != 0 || fsec != 0)
3586 int minus = (tm->tm_hour < 0 || tm->tm_min < 0 ||
3587 tm->tm_sec < 0 || fsec < 0);
3589 sprintf(cp, "%s%s%02d:%02d", is_nonzero ? " " : "",
3590 (minus ? "-" : (is_before ? "+" : "")),
3591 abs(tm->tm_hour), abs(tm->tm_min));
3593 /* Mark as "non-zero" since the fields are now filled in */
3596 /* need fractional seconds? */
3599 #ifdef HAVE_INT64_TIMESTAMP
3600 sprintf(cp, ":%02d", abs(tm->tm_sec));
3602 sprintf(cp, ".%06d", Abs(fsec));
3605 sprintf(cp, ":%012.9f", fabs(fsec));
3607 TrimTrailingZeros(cp);
3612 sprintf(cp, ":%02d", abs(tm->tm_sec));
3618 case USE_POSTGRES_DATES:
3623 if (tm->tm_year != 0)
3625 int year = tm->tm_year;
3627 if (tm->tm_year < 0)
3630 sprintf(cp, "%d year%s", year,
3631 (year != 1) ? "s" : "");
3633 is_before = (tm->tm_year < 0);
3637 if (tm->tm_mon != 0)
3639 int mon = tm->tm_mon;
3641 if (is_before || (!is_nonzero && tm->tm_mon < 0))
3644 sprintf(cp, "%s%d mon%s", is_nonzero ? " " : "", mon,
3645 (mon != 1) ? "s" : "");
3648 is_before = (tm->tm_mon < 0);
3652 if (tm->tm_mday != 0)
3654 int day = tm->tm_mday;
3656 if (is_before || (!is_nonzero && tm->tm_mday < 0))
3659 sprintf(cp, "%s%d day%s", is_nonzero ? " " : "", day,
3660 (day != 1) ? "s" : "");
3663 is_before = (tm->tm_mday < 0);
3666 if (tm->tm_hour != 0)
3668 int hour = tm->tm_hour;
3670 if (is_before || (!is_nonzero && tm->tm_hour < 0))
3673 sprintf(cp, "%s%d hour%s", is_nonzero ? " " : "", hour,
3674 (hour != 1) ? "s" : "");
3677 is_before = (tm->tm_hour < 0);
3681 if (tm->tm_min != 0)
3683 int min = tm->tm_min;
3685 if (is_before || (!is_nonzero && tm->tm_min < 0))
3688 sprintf(cp, "%s%d min%s", is_nonzero ? " " : "", min,
3689 (min != 1) ? "s" : "");
3692 is_before = (tm->tm_min < 0);
3696 /* fractional seconds? */
3701 #ifdef HAVE_INT64_TIMESTAMP
3703 if (is_before || (!is_nonzero && tm->tm_sec < 0))
3705 tm->tm_sec = -tm->tm_sec;
3709 else if (!is_nonzero && tm->tm_sec == 0 && fsec < 0)
3714 sprintf(cp, "%s%d.%02d secs", is_nonzero ? " " : "",
3715 tm->tm_sec, ((int) sec) / 10000);
3720 if (is_before || (!is_nonzero && fsec < 0))
3723 sprintf(cp, "%s%.2f secs", is_nonzero ? " " : "", sec);
3726 is_before = (fsec < 0);
3730 /* otherwise, integer seconds only? */
3731 else if (tm->tm_sec != 0)
3733 int sec = tm->tm_sec;
3735 if (is_before || (!is_nonzero && tm->tm_sec < 0))
3738 sprintf(cp, "%s%d sec%s", is_nonzero ? " " : "", sec,
3739 (sec != 1) ? "s" : "");
3742 is_before = (tm->tm_sec < 0);
3748 /* identically zero? then put in a unitless zero... */
3755 if (is_before && (style != USE_ISO_DATES))
3762 } /* EncodeInterval() */
3766 * We've been burnt by stupid errors in the ordering of the datetkn tables
3767 * once too often. Arrange to check them during postmaster start.
3770 CheckDateTokenTable(const char *tablename, const datetkn *base, int nel)
3775 for (i = 1; i < nel; i++)
3777 if (strncmp(base[i - 1].token, base[i].token, TOKMAXLEN) >= 0)
3779 elog(LOG, "ordering error in %s table: \"%.*s\" >= \"%.*s\"",
3781 TOKMAXLEN, base[i - 1].token,
3782 TOKMAXLEN, base[i].token);
3790 CheckDateTokenTables(void)
3794 Assert(UNIX_EPOCH_JDATE == date2j(1970, 1, 1));
3795 Assert(POSTGRES_EPOCH_JDATE == date2j(2000, 1, 1));
3797 ok &= CheckDateTokenTable("datetktbl", datetktbl, szdatetktbl);
3798 ok &= CheckDateTokenTable("deltatktbl", deltatktbl, szdeltatktbl);
3803 * This function gets called during timezone config file load or reload
3804 * to create the final array of timezone tokens. The argument array
3805 * is already sorted in name order. This data is in a temporary memory
3806 * context and must be copied to somewhere permanent.
3809 InstallTimeZoneAbbrevs(tzEntry *abbrevs, int n)
3815 * Copy the data into TopMemoryContext and convert to datetkn format.
3817 newtbl = (datetkn *) MemoryContextAlloc(TopMemoryContext,
3818 n * sizeof(datetkn));
3819 for (i = 0; i < n; i++)
3821 strncpy(newtbl[i].token, abbrevs[i].abbrev, TOKMAXLEN);
3822 newtbl[i].type = abbrevs[i].is_dst ? DTZ : TZ;
3823 TOVAL(&newtbl[i], abbrevs[i].offset / 60);
3826 /* Check the ordering, if testing */
3827 Assert(CheckDateTokenTable("timezone offset", newtbl, n));
3829 /* Now safe to replace existing table (if any) */
3831 pfree(timezonetktbl);
3832 timezonetktbl = newtbl;
3833 sztimezonetktbl = n;
3835 /* clear date cache in case it contains any stale timezone names */
3836 for (i = 0; i < MAXDATEFIELDS; i++)
3837 datecache[i] = NULL;
3841 * This set-returning function reads all the available time zone abbreviations
3842 * and returns a set of (abbrev, utc_offset, is_dst).
3845 pg_timezone_abbrevs(PG_FUNCTION_ARGS)
3847 FuncCallContext *funcctx;
3853 char buffer[TOKMAXLEN + 1];
3856 Interval *resInterval;
3858 /* stuff done only on the first call of the function */
3859 if (SRF_IS_FIRSTCALL())
3862 MemoryContext oldcontext;
3864 /* create a function context for cross-call persistence */
3865 funcctx = SRF_FIRSTCALL_INIT();
3868 * switch to memory context appropriate for multiple function calls
3870 oldcontext = MemoryContextSwitchTo(funcctx->multi_call_memory_ctx);
3872 /* allocate memory for user context */
3873 pindex = (int *) palloc(sizeof(int));
3875 funcctx->user_fctx = (void *) pindex;
3878 * build tupdesc for result tuples. This must match this function's
3881 tupdesc = CreateTemplateTupleDesc(3, false);
3882 TupleDescInitEntry(tupdesc, (AttrNumber) 1, "abbrev",
3884 TupleDescInitEntry(tupdesc, (AttrNumber) 2, "utc_offset",
3885 INTERVALOID, -1, 0);
3886 TupleDescInitEntry(tupdesc, (AttrNumber) 3, "is_dst",
3889 funcctx->tuple_desc = BlessTupleDesc(tupdesc);
3890 MemoryContextSwitchTo(oldcontext);
3893 /* stuff done on every call of the function */
3894 funcctx = SRF_PERCALL_SETUP();
3895 pindex = (int *) funcctx->user_fctx;
3897 if (*pindex >= sztimezonetktbl)
3898 SRF_RETURN_DONE(funcctx);
3900 MemSet(nulls, 0, sizeof(nulls));
3903 * Convert name to text, using upcasing conversion that is the inverse of
3904 * what ParseDateTime() uses.
3906 strncpy(buffer, timezonetktbl[*pindex].token, TOKMAXLEN);
3907 buffer[TOKMAXLEN] = '\0'; /* may not be null-terminated */
3908 for (p = (unsigned char *) buffer; *p; p++)
3909 *p = pg_toupper(*p);
3911 values[0] = DirectFunctionCall1(textin, CStringGetDatum(buffer));
3913 MemSet(&tm, 0, sizeof(struct pg_tm));
3914 tm.tm_min = (-1) * FROMVAL(&timezonetktbl[*pindex]);
3915 resInterval = (Interval *) palloc(sizeof(Interval));
3916 tm2interval(&tm, 0, resInterval);
3917 values[1] = IntervalPGetDatum(resInterval);
3919 Assert(timezonetktbl[*pindex].type == DTZ ||
3920 timezonetktbl[*pindex].type == TZ);
3921 values[2] = BoolGetDatum(timezonetktbl[*pindex].type == DTZ);
3925 tuple = heap_form_tuple(funcctx->tuple_desc, values, nulls);
3926 result = HeapTupleGetDatum(tuple);
3928 SRF_RETURN_NEXT(funcctx, result);
3932 * This set-returning function reads all the available full time zones
3933 * and returns a set of (name, abbrev, utc_offset, is_dst).
3936 pg_timezone_names(PG_FUNCTION_ARGS)
3938 MemoryContext oldcontext;
3939 FuncCallContext *funcctx;
3950 Interval *resInterval;
3953 /* stuff done only on the first call of the function */
3954 if (SRF_IS_FIRSTCALL())
3958 /* create a function context for cross-call persistence */
3959 funcctx = SRF_FIRSTCALL_INIT();
3962 * switch to memory context appropriate for multiple function calls
3964 oldcontext = MemoryContextSwitchTo(funcctx->multi_call_memory_ctx);
3966 /* initialize timezone scanning code */
3967 tzenum = pg_tzenumerate_start();
3968 funcctx->user_fctx = (void *) tzenum;
3971 * build tupdesc for result tuples. This must match this function's
3974 tupdesc = CreateTemplateTupleDesc(4, false);
3975 TupleDescInitEntry(tupdesc, (AttrNumber) 1, "name",
3977 TupleDescInitEntry(tupdesc, (AttrNumber) 2, "abbrev",
3979 TupleDescInitEntry(tupdesc, (AttrNumber) 3, "utc_offset",
3980 INTERVALOID, -1, 0);
3981 TupleDescInitEntry(tupdesc, (AttrNumber) 4, "is_dst",
3984 funcctx->tuple_desc = BlessTupleDesc(tupdesc);
3985 MemoryContextSwitchTo(oldcontext);
3988 /* stuff done on every call of the function */
3989 funcctx = SRF_PERCALL_SETUP();
3990 tzenum = (pg_tzenum *) funcctx->user_fctx;
3992 /* search for another zone to display */
3995 oldcontext = MemoryContextSwitchTo(funcctx->multi_call_memory_ctx);
3996 tz = pg_tzenumerate_next(tzenum);
3997 MemoryContextSwitchTo(oldcontext);
4001 pg_tzenumerate_end(tzenum);
4002 funcctx->user_fctx = NULL;
4003 SRF_RETURN_DONE(funcctx);
4006 /* Convert now() to local time in this zone */
4007 if (timestamp2tm(GetCurrentTransactionStartTimestamp(),
4008 &tzoff, &tm, &fsec, &tzn, tz) != 0)
4009 continue; /* ignore if conversion fails */
4011 /* Ignore zic's rather silly "Factory" time zone */
4012 if (tzn && strcmp(tzn, "Local time zone must be set--see zic manual page") == 0)
4015 /* Found a displayable zone */
4019 MemSet(nulls, 0, sizeof(nulls));
4021 values[0] = DirectFunctionCall1(textin,
4022 CStringGetDatum(pg_get_timezone_name(tz)));
4024 values[1] = DirectFunctionCall1(textin,
4025 CStringGetDatum(tzn ? tzn : ""));
4027 MemSet(&itm, 0, sizeof(struct pg_tm));
4028 itm.tm_sec = -tzoff;
4029 resInterval = (Interval *) palloc(sizeof(Interval));
4030 tm2interval(&itm, 0, resInterval);
4031 values[2] = IntervalPGetDatum(resInterval);
4033 values[3] = BoolGetDatum(tm.tm_isdst > 0);
4035 tuple = heap_form_tuple(funcctx->tuple_desc, values, nulls);
4036 result = HeapTupleGetDatum(tuple);
4038 SRF_RETURN_NEXT(funcctx, result);