dt.c 96.5 KB
Newer Older
1 2 3
/*-------------------------------------------------------------------------
 *
 * dt.c--
4
 *	  Functions for the built-in type "dt".
5 6 7 8 9
 *
 * Copyright (c) 1994, Regents of the University of California
 *
 *
 * IDENTIFICATION
10
 *	  $Header: /cvsroot/pgsql/src/backend/utils/adt/Attic/dt.c,v 1.60 1998/12/31 16:30:57 thomas Exp $
11 12 13
 *
 *-------------------------------------------------------------------------
 */
14 15 16 17 18
#include <stdio.h>
#include <ctype.h>
#include <math.h>
#include <string.h>
#include <sys/types.h>
19
#include <errno.h>
20

21
#include "postgres.h"
22
#include "miscadmin.h"
23
#ifdef HAVE_FLOAT_H
24
#include <float.h>
25
#endif
26
#ifdef HAVE_LIMITS_H
27
#include <limits.h>
28
#endif
29 30 31
#ifndef USE_POSIX_TIME
#include <sys/timeb.h>
#endif
32 33
#include "utils/builtins.h"

34
static int	DecodeDate(char *str, int fmask, int *tmask, struct tm * tm);
35
static int DecodeNumber(int flen, char *field,
36
			 int fmask, int *tmask, struct tm * tm, double *fsec);
37
static int DecodeNumberField(int len, char *str,
38
				  int fmask, int *tmask, struct tm * tm, double *fsec);
39
static int	DecodeSpecial(int field, char *lowtoken, int *val);
40
static int DecodeTime(char *str, int fmask, int *tmask,
41
		   struct tm * tm, double *fsec);
42 43 44
static int	DecodeTimezone(char *str, int *tzp);
static int	DecodeUnits(int field, char *lowtoken, int *val);
static int	EncodeSpecialDateTime(DateTime dt, char *str);
45
static datetkn *datebsearch(char *key, datetkn *base, unsigned int nel);
46
static DateTime dt2local(DateTime dt, int timezone);
47
static void dt2time(DateTime dt, int *hour, int *min, double *sec);
48
static int	j2day(int jd);
49 50 51
static double time2t(const int hour, const int min, const double sec);
static int	timespan2tm(TimeSpan span, struct tm * tm, float8 *fsec);
static int	tm2timespan(struct tm * tm, double fsec, TimeSpan *span);
52

53
#define USE_DATE_CACHE 1
54
#define ROUND_ALL 0
55

56 57
#define isleap(y) (((y % 4) == 0) && (((y % 100) != 0) || ((y % 400) == 0)))

58
int			mdays[] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31, 0};
59

60
char	   *months[] = {"Jan", "Feb", "Mar", "Apr", "May", "Jun",
61
"Jul", "Aug", "Sep", "Oct", "Nov", "Dec", NULL};
62

63
char	   *days[] = {"Sunday", "Monday", "Tuesday", "Wednesday",
64
"Thursday", "Friday", "Saturday", NULL};
65

66 67 68
/* TMODULO()
 * Macro to replace modf(), which is broken on some platforms.
 */
69 70 71 72 73 74
#define TMODULO(t,q,u) \
do { \
	q = ((t < 0)? ceil(t / u): floor(t / u)); \
	if (q != 0) \
		t -= rint(q * u); \
} while(0)
75

76
static void GetEpochTime(struct tm * tm);
77 78 79 80 81 82 83 84 85 86 87 88 89 90

#define UTIME_MINYEAR (1901)
#define UTIME_MINMONTH (12)
#define UTIME_MINDAY (14)
#define UTIME_MAXYEAR (2038)
#define UTIME_MAXMONTH (01)
#define UTIME_MAXDAY (18)

#define IS_VALID_UTIME(y,m,d) (((y > UTIME_MINYEAR) \
 || ((y == UTIME_MINYEAR) && ((m > UTIME_MINMONTH) \
  || ((m == UTIME_MINMONTH) && (d >= UTIME_MINDAY))))) \
 && ((y < UTIME_MAXYEAR) \
 || ((y == UTIME_MAXYEAR) && ((m < UTIME_MAXMONTH) \
  || ((m == UTIME_MAXMONTH) && (d <= UTIME_MAXDAY))))))
91

92

93 94
/*****************************************************************************
 *	 USER I/O ROUTINES														 *
95 96
 *****************************************************************************/

97 98
/* datetime_in()
 * Convert a string to internal form.
99
 */
100
DateTime   *
101
datetime_in(char *str)
102
{
103 104 105 106 107 108 109 110 111 112 113
	DateTime   *result;

	double		fsec;
	struct tm	tt,
			   *tm = &tt;
	int			tz;
	int			dtype;
	int			nf;
	char	   *field[MAXDATEFIELDS];
	int			ftype[MAXDATEFIELDS];
	char		lowstr[MAXDATELEN + 1];
114

115
	if (!PointerIsValid(str))
116
		elog(ERROR, "Bad (null) datetime external representation", NULL);
117

118 119
	if ((ParseDateTime(str, lowstr, field, ftype, MAXDATEFIELDS, &nf) != 0)
	  || (DecodeDateTime(field, ftype, nf, &dtype, tm, &fsec, &tz) != 0))
120
		elog(ERROR, "Bad datetime external representation '%s'", str);
121

122
	result = palloc(sizeof(DateTime));
123

124 125
	switch (dtype)
	{
126 127
		case DTK_DATE:
			if (tm2datetime(tm, fsec, &tz, result) != 0)
128
				elog(ERROR, "Datetime out of range '%s'", str);
129

130
#ifdef DATEDEBUG
131
			printf("datetime_in- date is %f\n", *result);
132 133
#endif

134
			break;
135

136 137 138
		case DTK_EPOCH:
			DATETIME_EPOCH(*result);
			break;
139

140 141 142
		case DTK_CURRENT:
			DATETIME_CURRENT(*result);
			break;
143

144 145 146
		case DTK_LATE:
			DATETIME_NOEND(*result);
			break;
147

148 149 150
		case DTK_EARLY:
			DATETIME_NOBEGIN(*result);
			break;
151

152 153 154
		case DTK_INVALID:
			DATETIME_INVALID(*result);
			break;
155

156
		default:
157
			elog(ERROR, "Internal coding error, can't input datetime '%s'", str);
158
	}
159

160
	return result;
161
}	/* datetime_in() */
162 163 164 165

/* datetime_out()
 * Convert a datetime to external form.
 */
166
char *
167
datetime_out(DateTime *dt)
168
{
169 170 171 172 173 174 175
	char	   *result;
	int			tz;
	struct tm	tt,
			   *tm = &tt;
	double		fsec;
	char	   *tzn;
	char		buf[MAXDATELEN + 1];
176

177
	if (!PointerIsValid(dt))
178
		return NULL;
179

180 181 182
	if (DATETIME_IS_RESERVED(*dt))
	{
		EncodeSpecialDateTime(*dt, buf);
183

184 185 186 187
	}
	else if (datetime2tm(*dt, &tz, tm, &fsec, &tzn) == 0)
	{
		EncodeDateTime(tm, fsec, &tz, &tzn, DateStyle, buf);
188

189 190 191
	}
	else
		EncodeSpecialDateTime(DT_INVALID, buf);
192

193
	result = palloc(strlen(buf) + 1);
194

195
	strcpy(result, buf);
196

197
	return result;
198
}	/* datetime_out() */
199 200 201 202


/* timespan_in()
 * Convert a string to internal form.
203
 *
204
 * External format(s):
205
 *	Uses the generic date/time parsing and decoding routines.
206
 */
207
TimeSpan   *
208
timespan_in(char *str)
209
{
210
	TimeSpan   *span;
211

212 213 214 215 216 217 218 219
	double		fsec;
	struct tm	tt,
			   *tm = &tt;
	int			dtype;
	int			nf;
	char	   *field[MAXDATEFIELDS];
	int			ftype[MAXDATEFIELDS];
	char		lowstr[MAXDATELEN + 1];
220

221 222 223 224 225 226 227
	tm->tm_year = 0;
	tm->tm_mon = 0;
	tm->tm_mday = 0;
	tm->tm_hour = 0;
	tm->tm_min = 0;
	tm->tm_sec = 0;
	fsec = 0;
228

229
	if (!PointerIsValid(str))
230
		elog(ERROR, "Bad (null) timespan external representation", NULL);
231

232 233
	if ((ParseDateTime(str, lowstr, field, ftype, MAXDATEFIELDS, &nf) != 0)
		|| (DecodeDateDelta(field, ftype, nf, &dtype, tm, &fsec) != 0))
234
		elog(ERROR, "Bad timespan external representation '%s'", str);
235

236
	span = palloc(sizeof(TimeSpan));
237

238 239
	switch (dtype)
	{
240 241 242
		case DTK_DELTA:
			if (tm2timespan(tm, fsec, span) != 0)
			{
243
#if FALSE
244
				TIMESPAN_INVALID(span);
245
#endif
246
				elog(ERROR, "Bad timespan external representation '%s'", str);
247 248
			}
			break;
249

250
		default:
251
			elog(ERROR, "Internal coding error, can't input timespan '%s'", str);
252
	}
253

254
	return span;
255
}	/* timespan_in() */
256 257 258 259

/* timespan_out()
 * Convert a time span to external form.
 */
260
char *
261
timespan_out(TimeSpan *span)
262
{
263
	char	   *result;
264

265 266 267 268
	struct tm	tt,
			   *tm = &tt;
	double		fsec;
	char		buf[MAXDATELEN + 1];
269

270
	if (!PointerIsValid(span))
271
		return NULL;
272

273
	if (timespan2tm(*span, tm, &fsec) != 0)
274
		return NULL;
275

276
	if (EncodeTimeSpan(tm, fsec, DateStyle, buf) != 0)
277
		elog(ERROR, "Unable to format timespan", NULL);
278

279
	result = palloc(strlen(buf) + 1);
280

281
	strcpy(result, buf);
282
	return result;
283
}	/* timespan_out() */
284 285


286 287
/*****************************************************************************
 *	 PUBLIC ROUTINES														 *
288 289 290
 *****************************************************************************/


291
bool
292
datetime_finite(DateTime *datetime)
293
{
294 295
	if (!PointerIsValid(datetime))
		return FALSE;
296

297
	return !DATETIME_NOT_FINITE(*datetime);
298
}	/* datetime_finite() */
299 300

bool
301
timespan_finite(TimeSpan *timespan)
302
{
303 304 305
	if (!PointerIsValid(timespan))
		return FALSE;

306
	return !TIMESPAN_NOT_FINITE(*timespan);
307
}	/* timespan_finite() */
308 309


310
/*----------------------------------------------------------
311
 *	Relational operators for datetime.
312 313
 *---------------------------------------------------------*/

314
static void
315
GetEpochTime(struct tm * tm)
316
{
317 318
	struct tm  *t0;
	time_t		epoch = 0;
319

320
	t0 = gmtime(&epoch);
321

322 323 324 325 326 327
	tm->tm_year = t0->tm_year;
	tm->tm_mon = t0->tm_mon;
	tm->tm_mday = t0->tm_mday;
	tm->tm_hour = t0->tm_hour;
	tm->tm_min = t0->tm_min;
	tm->tm_sec = t0->tm_sec;
328

329 330 331
	if (tm->tm_year < 1900)
		tm->tm_year += 1900;
	tm->tm_mon++;
332 333

#ifdef DATEDEBUG
334 335
	printf("GetEpochTime- %04d-%02d-%02d %02d:%02d:%02d\n",
		   tm->tm_year, tm->tm_mon, tm->tm_mday, tm->tm_hour, tm->tm_min, tm->tm_sec);
336 337
#endif

338
	return;
339
}	/* GetEpochTime() */
340 341

DateTime
342 343
SetDateTime(DateTime dt)
{
344
	struct tm	tt;
345

346 347 348 349 350
	if (DATETIME_IS_CURRENT(dt))
	{
		GetCurrentTime(&tt);
		tm2datetime(&tt, 0, NULL, &dt);
		dt = dt2local(dt, -CTimeZone);
351 352

#ifdef DATEDEBUG
353
		printf("SetDateTime- current time is %f\n", dt);
354
#endif
355 356 357 358 359
	}
	else
	{							/* if (DATETIME_IS_EPOCH(dt1)) */
		GetEpochTime(&tt);
		tm2datetime(&tt, 0, NULL, &dt);
360
#ifdef DATEDEBUG
361
		printf("SetDateTime- epoch time is %f\n", dt);
362
#endif
363
	}
364

365
	return dt;
366
}	/* SetDateTime() */
367

368
/*		datetime_relop	- is datetime1 relop datetime2
369 370
 */
bool
371
datetime_eq(DateTime *datetime1, DateTime *datetime2)
372
{
373 374
	DateTime	dt1,
				dt2;
375

376 377
	if (!PointerIsValid(datetime1) || !PointerIsValid(datetime2))
		return FALSE;
378

379 380
	dt1 = *datetime1;
	dt2 = *datetime2;
381

382 383
	if (DATETIME_IS_INVALID(dt1) || DATETIME_IS_INVALID(dt2))
		return FALSE;
384

385 386 387 388
	if (DATETIME_IS_RELATIVE(dt1))
		dt1 = SetDateTime(dt1);
	if (DATETIME_IS_RELATIVE(dt2))
		dt2 = SetDateTime(dt2);
389

390
	return dt1 == dt2;
391
}	/* datetime_eq() */
392 393

bool
394
datetime_ne(DateTime *datetime1, DateTime *datetime2)
395
{
396 397
	DateTime	dt1,
				dt2;
398

399 400
	if (!PointerIsValid(datetime1) || !PointerIsValid(datetime2))
		return FALSE;
401

402 403
	dt1 = *datetime1;
	dt2 = *datetime2;
404

405 406
	if (DATETIME_IS_INVALID(dt1) || DATETIME_IS_INVALID(dt2))
		return FALSE;
407

408 409 410 411
	if (DATETIME_IS_RELATIVE(dt1))
		dt1 = SetDateTime(dt1);
	if (DATETIME_IS_RELATIVE(dt2))
		dt2 = SetDateTime(dt2);
412

413
	return dt1 != dt2;
414
}	/* datetime_ne() */
415 416

bool
417
datetime_lt(DateTime *datetime1, DateTime *datetime2)
418
{
419 420
	DateTime	dt1,
				dt2;
421

422 423
	if (!PointerIsValid(datetime1) || !PointerIsValid(datetime2))
		return FALSE;
424

425 426
	dt1 = *datetime1;
	dt2 = *datetime2;
427

428 429
	if (DATETIME_IS_INVALID(dt1) || DATETIME_IS_INVALID(dt2))
		return FALSE;
430

431 432 433 434
	if (DATETIME_IS_RELATIVE(dt1))
		dt1 = SetDateTime(dt1);
	if (DATETIME_IS_RELATIVE(dt2))
		dt2 = SetDateTime(dt2);
435

436
	return dt1 < dt2;
437
}	/* datetime_lt() */
438 439

bool
440
datetime_gt(DateTime *datetime1, DateTime *datetime2)
441
{
442 443
	DateTime	dt1,
				dt2;
444

445 446
	if (!PointerIsValid(datetime1) || !PointerIsValid(datetime2))
		return FALSE;
447

448 449
	dt1 = *datetime1;
	dt2 = *datetime2;
450

451 452
	if (DATETIME_IS_INVALID(dt1) || DATETIME_IS_INVALID(dt2))
		return FALSE;
453

454 455 456 457
	if (DATETIME_IS_RELATIVE(dt1))
		dt1 = SetDateTime(dt1);
	if (DATETIME_IS_RELATIVE(dt2))
		dt2 = SetDateTime(dt2);
458 459

#ifdef DATEDEBUG
460
	printf("datetime_gt- %f %s greater than %f\n", dt1, ((dt1 > dt2) ? "is" : "is not"), dt2);
461
#endif
462
	return dt1 > dt2;
463
}	/* datetime_gt() */
464 465

bool
466
datetime_le(DateTime *datetime1, DateTime *datetime2)
467
{
468 469
	DateTime	dt1,
				dt2;
470

471 472
	if (!PointerIsValid(datetime1) || !PointerIsValid(datetime2))
		return FALSE;
473

474 475
	dt1 = *datetime1;
	dt2 = *datetime2;
476

477 478
	if (DATETIME_IS_INVALID(dt1) || DATETIME_IS_INVALID(dt2))
		return FALSE;
479

480 481 482 483
	if (DATETIME_IS_RELATIVE(dt1))
		dt1 = SetDateTime(dt1);
	if (DATETIME_IS_RELATIVE(dt2))
		dt2 = SetDateTime(dt2);
484

485
	return dt1 <= dt2;
486
}	/* datetime_le() */
487 488

bool
489
datetime_ge(DateTime *datetime1, DateTime *datetime2)
490
{
491 492
	DateTime	dt1,
				dt2;
493

494 495
	if (!PointerIsValid(datetime1) || !PointerIsValid(datetime2))
		return FALSE;
496

497 498
	dt1 = *datetime1;
	dt2 = *datetime2;
499

500 501
	if (DATETIME_IS_INVALID(dt1) || DATETIME_IS_INVALID(dt2))
		return FALSE;
502

503 504 505 506
	if (DATETIME_IS_RELATIVE(dt1))
		dt1 = SetDateTime(dt1);
	if (DATETIME_IS_RELATIVE(dt2))
		dt2 = SetDateTime(dt2);
507

508
	return dt1 >= dt2;
509
}	/* datetime_ge() */
510 511


512 513
/*		datetime_cmp	- 3-state comparison for datetime
 *		collate invalid datetime at the end
514 515
 */
int
516
datetime_cmp(DateTime *datetime1, DateTime *datetime2)
517
{
518 519
	DateTime	dt1,
				dt2;
520

521 522
	if (!PointerIsValid(datetime1) || !PointerIsValid(datetime2))
		return 0;
523

524 525
	dt1 = *datetime1;
	dt2 = *datetime2;
526

527 528
	if (DATETIME_IS_INVALID(dt1))
	{
529
		return (DATETIME_IS_INVALID(dt2) ? 0 : 1);
530

531 532 533
	}
	else if (DATETIME_IS_INVALID(dt2))
	{
534
		return -1;
535

536 537 538 539 540 541 542 543
	}
	else
	{
		if (DATETIME_IS_RELATIVE(dt1))
			dt1 = SetDateTime(dt1);
		if (DATETIME_IS_RELATIVE(dt2))
			dt2 = SetDateTime(dt2);
	}
544

545
	return ((dt1 < dt2) ? -1 : ((dt1 > dt2) ? 1 : 0));
546
}	/* datetime_cmp() */
547 548


549
/*		timespan_relop	- is timespan1 relop timespan2
550 551
 */
bool
552
timespan_eq(TimeSpan *timespan1, TimeSpan *timespan2)
553
{
554 555
	if (!PointerIsValid(timespan1) || !PointerIsValid(timespan2))
		return FALSE;
556

557 558
	if (TIMESPAN_IS_INVALID(*timespan1) || TIMESPAN_IS_INVALID(*timespan2))
		return FALSE;
559

560 561
	return ((timespan1->time == timespan2->time)
			&& (timespan1->month == timespan2->month));
562
}	/* timespan_eq() */
563 564

bool
565
timespan_ne(TimeSpan *timespan1, TimeSpan *timespan2)
566
{
567 568
	if (!PointerIsValid(timespan1) || !PointerIsValid(timespan2))
		return FALSE;
569

570 571
	if (TIMESPAN_IS_INVALID(*timespan1) || TIMESPAN_IS_INVALID(*timespan2))
		return FALSE;
572

573 574
	return ((timespan1->time != timespan2->time)
			|| (timespan1->month != timespan2->month));
575
}	/* timespan_ne() */
576 577

bool
578
timespan_lt(TimeSpan *timespan1, TimeSpan *timespan2)
579
{
580 581
	double		span1,
				span2;
582

583 584
	if (!PointerIsValid(timespan1) || !PointerIsValid(timespan2))
		return FALSE;
585

586 587
	if (TIMESPAN_IS_INVALID(*timespan1) || TIMESPAN_IS_INVALID(*timespan2))
		return FALSE;
588

589 590 591 592 593 594
	span1 = timespan1->time;
	if (timespan1->month != 0)
		span1 += (timespan1->month * (30.0 * 86400));
	span2 = timespan2->time;
	if (timespan2->month != 0)
		span2 += (timespan2->month * (30.0 * 86400));
595

596
	return span1 < span2;
597
}	/* timespan_lt() */
598 599

bool
600
timespan_gt(TimeSpan *timespan1, TimeSpan *timespan2)
601
{
602 603
	double		span1,
				span2;
604

605 606
	if (!PointerIsValid(timespan1) || !PointerIsValid(timespan2))
		return FALSE;
607

608 609
	if (TIMESPAN_IS_INVALID(*timespan1) || TIMESPAN_IS_INVALID(*timespan2))
		return FALSE;
610

611 612 613 614 615 616
	span1 = timespan1->time;
	if (timespan1->month != 0)
		span1 += (timespan1->month * (30.0 * 86400));
	span2 = timespan2->time;
	if (timespan2->month != 0)
		span2 += (timespan2->month * (30.0 * 86400));
617

618
	return span1 > span2;
619
}	/* timespan_gt() */
620 621

bool
622
timespan_le(TimeSpan *timespan1, TimeSpan *timespan2)
623
{
624 625
	double		span1,
				span2;
626

627 628
	if (!PointerIsValid(timespan1) || !PointerIsValid(timespan2))
		return FALSE;
629

630 631
	if (TIMESPAN_IS_INVALID(*timespan1) || TIMESPAN_IS_INVALID(*timespan2))
		return FALSE;
632

633 634 635 636 637 638
	span1 = timespan1->time;
	if (timespan1->month != 0)
		span1 += (timespan1->month * (30.0 * 86400));
	span2 = timespan2->time;
	if (timespan2->month != 0)
		span2 += (timespan2->month * (30.0 * 86400));
639

640
	return span1 <= span2;
641
}	/* timespan_le() */
642 643

bool
644
timespan_ge(TimeSpan *timespan1, TimeSpan *timespan2)
645
{
646 647
	double		span1,
				span2;
648

649 650
	if (!PointerIsValid(timespan1) || !PointerIsValid(timespan2))
		return FALSE;
651

652 653
	if (TIMESPAN_IS_INVALID(*timespan1) || TIMESPAN_IS_INVALID(*timespan2))
		return FALSE;
654

655 656 657 658 659 660
	span1 = timespan1->time;
	if (timespan1->month != 0)
		span1 += (timespan1->month * (30.0 * 86400));
	span2 = timespan2->time;
	if (timespan2->month != 0)
		span2 += (timespan2->month * (30.0 * 86400));
661

662
	return span1 >= span2;
663
}	/* timespan_ge() */
664 665


666
/*		timespan_cmp	- 3-state comparison for timespan
667 668
 */
int
669
timespan_cmp(TimeSpan *timespan1, TimeSpan *timespan2)
670
{
671 672
	double		span1,
				span2;
673

674 675
	if (!PointerIsValid(timespan1) || !PointerIsValid(timespan2))
		return 0;
676

677 678
	if (TIMESPAN_IS_INVALID(*timespan1))
	{
679
		return TIMESPAN_IS_INVALID(*timespan2) ? 0 : 1;
680

681 682
	}
	else if (TIMESPAN_IS_INVALID(*timespan2))
683
		return -1;
684

685 686 687 688 689 690
	span1 = timespan1->time;
	if (timespan1->month != 0)
		span1 += (timespan1->month * (30.0 * 86400));
	span2 = timespan2->time;
	if (timespan2->month != 0)
		span2 += (timespan2->month * (30.0 * 86400));
691

692
	return (span1 < span2) ? -1 : (span1 > span2) ? 1 : 0;
693
}	/* timespan_cmp() */
694 695


696
/*----------------------------------------------------------
697 698 699 700 701
 *	"Arithmetic" operators on date/times.
 *		datetime_foo	returns foo as an object (pointer) that
 *						can be passed between languages.
 *		datetime_xx		is an internal routine which returns the
 *						actual value.
702 703
 *---------------------------------------------------------*/

704
DateTime   *
705
datetime_smaller(DateTime *datetime1, DateTime *datetime2)
706
{
707
	DateTime   *result;
708

709 710
	DateTime	dt1,
				dt2;
711

712 713
	if (!PointerIsValid(datetime1) || !PointerIsValid(datetime2))
		return NULL;
714

715 716
	dt1 = *datetime1;
	dt2 = *datetime2;
717

718
	result = palloc(sizeof(DateTime));
719

720 721 722 723
	if (DATETIME_IS_RELATIVE(dt1))
		dt1 = SetDateTime(dt1);
	if (DATETIME_IS_RELATIVE(dt2))
		dt2 = SetDateTime(dt2);
724

725 726 727 728 729 730
	if (DATETIME_IS_INVALID(dt1))
		*result = dt2;
	else if (DATETIME_IS_INVALID(dt2))
		*result = dt1;
	else
		*result = ((dt2 < dt1) ? dt2 : dt1);
731

732
	return result;
733
}	/* datetime_smaller() */
734

735
DateTime   *
736
datetime_larger(DateTime *datetime1, DateTime *datetime2)
737
{
738
	DateTime   *result;
739

740 741
	DateTime	dt1,
				dt2;
742

743 744
	if (!PointerIsValid(datetime1) || !PointerIsValid(datetime2))
		return NULL;
745

746 747
	dt1 = *datetime1;
	dt2 = *datetime2;
748

749
	result = palloc(sizeof(DateTime));
750

751 752 753 754
	if (DATETIME_IS_RELATIVE(dt1))
		dt1 = SetDateTime(dt1);
	if (DATETIME_IS_RELATIVE(dt2))
		dt2 = SetDateTime(dt2);
755

756 757 758 759 760 761
	if (DATETIME_IS_INVALID(dt1))
		*result = dt2;
	else if (DATETIME_IS_INVALID(dt2))
		*result = dt1;
	else
		*result = ((dt2 > dt1) ? dt2 : dt1);
762

763
	return result;
764
}	/* datetime_larger() */
765 766


767
TimeSpan   *
768
datetime_mi(DateTime *datetime1, DateTime *datetime2)
769
{
770
	TimeSpan   *result;
771

772 773
	DateTime	dt1,
				dt2;
774

775 776
	if (!PointerIsValid(datetime1) || !PointerIsValid(datetime2))
		return NULL;
777

778 779
	dt1 = *datetime1;
	dt2 = *datetime2;
780

781
	result = palloc(sizeof(TimeSpan));
782

783 784 785 786
	if (DATETIME_IS_RELATIVE(dt1))
		dt1 = SetDateTime(dt1);
	if (DATETIME_IS_RELATIVE(dt2))
		dt2 = SetDateTime(dt2);
787

788
#ifdef DATEDEBUG
789
	printf("datetime_mi- evaluate %f - %f\n", dt1, dt2);
790 791
#endif

792 793 794 795
	if (DATETIME_IS_INVALID(dt1)
		|| DATETIME_IS_INVALID(dt2))
	{
		DATETIME_INVALID(result->time);
796

797 798 799 800
	}
	else
		result->time = JROUND(dt1 - dt2);
	result->month = 0;
801

802
	return result;
803
}	/* datetime_mi() */
804 805


806
/* datetime_pl_span()
807 808
 * Add a timespan to a datetime data type.
 * Note that timespan has provisions for qualitative year/month
809
 *	units, so try to do the right thing with them.
810 811
 * To add a month, increment the month, and use the same day of month.
 * Then, if the next month has fewer days, set the day of month
812
 *	to the last day of month.
813
 */
814
DateTime   *
815
datetime_pl_span(DateTime *datetime, TimeSpan *span)
816
{
817 818 819 820
	DateTime   *result;
	DateTime	dt;
	int			tz;
	char	   *tzn;
821

822 823
	if ((!PointerIsValid(datetime)) || (!PointerIsValid(span)))
		return NULL;
824

825
	result = palloc(sizeof(DateTime));
826 827

#ifdef DATEDEBUG
828
	printf("datetime_pl_span- add %f to %d %f\n", *datetime, span->month, span->time);
829 830
#endif

831 832 833
	if (DATETIME_NOT_FINITE(*datetime))
	{
		*result = *datetime;
834

835 836 837 838
	}
	else if (TIMESPAN_IS_INVALID(*span))
	{
		DATETIME_INVALID(*result);
839

840 841 842 843
	}
	else
	{
		dt = (DATETIME_IS_RELATIVE(*datetime) ? SetDateTime(*datetime) : *datetime);
844 845

#ifdef ROUND_ALL
846
		dt = JROUND(dt + span->time);
847
#else
848
		dt += span->time;
849
#endif
850

851 852
		if (span->month != 0)
		{
853 854 855
			struct tm	tt,
					   *tm = &tt;
			double		fsec;
856

857 858
			if (datetime2tm(dt, &tz, tm, &fsec, &tzn) == 0)
			{
859
#ifdef DATEDEBUG
860 861
				printf("datetime_pl_span- date was %04d-%02d-%02d %02d:%02d:%02d\n",
					   tm->tm_year, tm->tm_mon, tm->tm_mday, tm->tm_hour, tm->tm_min, tm->tm_sec);
862
#endif
863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882
				tm->tm_mon += span->month;
				if (tm->tm_mon > 12)
				{
					tm->tm_year += ((tm->tm_mon - 1) / 12);
					tm->tm_mon = (((tm->tm_mon - 1) % 12) + 1);
				}
				else if (tm->tm_mon < 1)
				{
					tm->tm_year += ((tm->tm_mon / 12) - 1);
					tm->tm_mon = ((tm->tm_mon % 12) + 12);
				}

				/* adjust for end of month boundary problems... */
				if (tm->tm_mday > mdays[tm->tm_mon - 1])
				{
					if ((tm->tm_mon == 2) && isleap(tm->tm_year))
						tm->tm_mday = (mdays[tm->tm_mon - 1] + 1);
					else
						tm->tm_mday = mdays[tm->tm_mon - 1];
				}
883

884
#ifdef DATEDEBUG
885 886
				printf("datetime_pl_span- date becomes %04d-%02d-%02d %02d:%02d:%02d\n",
					   tm->tm_year, tm->tm_mon, tm->tm_mday, tm->tm_hour, tm->tm_min, tm->tm_sec);
887
#endif
888
				if (tm2datetime(tm, fsec, &tz, &dt) != 0)
889
					elog(ERROR, "Unable to add datetime and timespan", NULL);
890 891 892 893 894

			}
			else
				DATETIME_INVALID(dt);
		}
895

896
		*result = dt;
897
	}
898

899
	return result;
900
}	/* datetime_pl_span() */
901

902
DateTime   *
903
datetime_mi_span(DateTime *datetime, TimeSpan *span)
904
{
905 906
	DateTime   *result;
	TimeSpan	tspan;
907

908 909
	if (!PointerIsValid(datetime) || !PointerIsValid(span))
		return NULL;
910

911 912
	tspan.month = -span->month;
	tspan.time = -span->time;
913

914
	result = datetime_pl_span(datetime, &tspan);
915

916
	return result;
917
}	/* datetime_mi_span() */
918 919


920
TimeSpan   *
921
timespan_um(TimeSpan *timespan)
922
{
923
	TimeSpan   *result;
924

925 926
	if (!PointerIsValid(timespan))
		return NULL;
927

928
	result = palloc(sizeof(TimeSpan));
929

930 931
	result->time = -(timespan->time);
	result->month = -(timespan->month);
932

933
	return result;
934
}	/* timespan_um() */
935 936


937
TimeSpan   *
938
timespan_smaller(TimeSpan *timespan1, TimeSpan *timespan2)
939
{
940
	TimeSpan   *result;
941

942 943
	double		span1,
				span2;
944

945 946
	if (!PointerIsValid(timespan1) || !PointerIsValid(timespan2))
		return NULL;
947

948
	result = palloc(sizeof(TimeSpan));
949

950 951 952 953
	if (TIMESPAN_IS_INVALID(*timespan1))
	{
		result->time = timespan2->time;
		result->month = timespan2->month;
954

955 956 957 958 959
	}
	else if (TIMESPAN_IS_INVALID(*timespan2))
	{
		result->time = timespan1->time;
		result->month = timespan1->month;
960

961 962 963 964 965 966 967 968 969
	}
	else
	{
		span1 = timespan1->time;
		if (timespan1->month != 0)
			span1 += (timespan1->month * (30.0 * 86400));
		span2 = timespan2->time;
		if (timespan2->month != 0)
			span2 += (timespan2->month * (30.0 * 86400));
970 971

#ifdef DATEDEBUG
972 973
		printf("timespan_smaller- months %d %d times %f %f spans %f %f\n",
			   timespan1->month, timespan2->month, timespan1->time, timespan2->time, span1, span2);
974 975
#endif

976 977 978 979
		if (span2 < span1)
		{
			result->time = timespan2->time;
			result->month = timespan2->month;
980

981 982 983 984 985 986
		}
		else
		{
			result->time = timespan1->time;
			result->month = timespan1->month;
		}
987
	}
988

989
	return result;
990
}	/* timespan_smaller() */
991

992
TimeSpan   *
993
timespan_larger(TimeSpan *timespan1, TimeSpan *timespan2)
994
{
995
	TimeSpan   *result;
996

997 998
	double		span1,
				span2;
999

1000 1001
	if (!PointerIsValid(timespan1) || !PointerIsValid(timespan2))
		return NULL;
1002

1003
	result = palloc(sizeof(TimeSpan));
1004

1005 1006 1007 1008
	if (TIMESPAN_IS_INVALID(*timespan1))
	{
		result->time = timespan2->time;
		result->month = timespan2->month;
1009

1010 1011 1012 1013 1014
	}
	else if (TIMESPAN_IS_INVALID(*timespan2))
	{
		result->time = timespan1->time;
		result->month = timespan1->month;
1015

1016 1017 1018 1019 1020 1021 1022 1023 1024
	}
	else
	{
		span1 = timespan1->time;
		if (timespan1->month != 0)
			span1 += (timespan1->month * (30.0 * 86400));
		span2 = timespan2->time;
		if (timespan2->month != 0)
			span2 += (timespan2->month * (30.0 * 86400));
1025 1026

#ifdef DATEDEBUG
1027 1028
		printf("timespan_larger- months %d %d times %f %f spans %f %f\n",
			   timespan1->month, timespan2->month, timespan1->time, timespan2->time, span1, span2);
1029 1030
#endif

1031 1032 1033 1034
		if (span2 > span1)
		{
			result->time = timespan2->time;
			result->month = timespan2->month;
1035

1036 1037 1038 1039 1040 1041
		}
		else
		{
			result->time = timespan1->time;
			result->month = timespan1->month;
		}
1042
	}
1043

1044
	return result;
1045
}	/* timespan_larger() */
1046 1047


1048
TimeSpan   *
1049
timespan_pl(TimeSpan *span1, TimeSpan *span2)
1050
{
1051
	TimeSpan   *result;
1052

1053 1054
	if ((!PointerIsValid(span1)) || (!PointerIsValid(span2)))
		return NULL;
1055

1056
	result = palloc(sizeof(TimeSpan));
1057

1058 1059
	result->month = (span1->month + span2->month);
	result->time = JROUND(span1->time + span2->time);
1060

1061
	return result;
1062
}	/* timespan_pl() */
1063

1064
TimeSpan   *
1065
timespan_mi(TimeSpan *span1, TimeSpan *span2)
1066
{
1067
	TimeSpan   *result;
1068

1069 1070
	if ((!PointerIsValid(span1)) || (!PointerIsValid(span2)))
		return NULL;
1071

1072
	result = palloc(sizeof(TimeSpan));
1073

1074 1075
	result->month = (span1->month - span2->month);
	result->time = JROUND(span1->time - span2->time);
1076

1077
	return result;
1078
}	/* timespan_mi() */
1079

1080
TimeSpan   *
1081
timespan_div(TimeSpan *span1, float8 *arg2)
1082
{
1083
	TimeSpan   *result;
1084

1085 1086
	if ((!PointerIsValid(span1)) || (!PointerIsValid(arg2)))
		return NULL;
1087

1088
	if (!PointerIsValid(result = palloc(sizeof(TimeSpan))))
1089
		elog(ERROR, "Memory allocation failed, can't subtract timespans", NULL);
1090

1091
	if (*arg2 == 0.0)
1092
		elog(ERROR, "timespan_div:  divide by 0.0 error");
1093

1094 1095
	result->month = rint(span1->month / *arg2);
	result->time = JROUND(span1->time / *arg2);
1096

1097
	return result;
1098
}	/* timespan_div() */
1099

1100 1101 1102
/* datetime_age()
 * Calculate time difference while retaining year/month fields.
 * Note that this does not result in an accurate absolute time span
1103 1104
 *	since year and month are out of context once the arithmetic
 *	is done.
1105
 */
1106
TimeSpan   *
1107
datetime_age(DateTime *datetime1, DateTime *datetime2)
1108
{
1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121
	TimeSpan   *result;

	DateTime	dt1,
				dt2;
	double		fsec,
				fsec1,
				fsec2;
	struct tm	tt,
			   *tm = &tt;
	struct tm	tt1,
			   *tm1 = &tt1;
	struct tm	tt2,
			   *tm2 = &tt2;
1122 1123 1124 1125

	if (!PointerIsValid(datetime1) || !PointerIsValid(datetime2))
		return NULL;

1126
	result = palloc(sizeof(TimeSpan));
1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139

	dt1 = *datetime1;
	dt2 = *datetime2;

	if (DATETIME_IS_RELATIVE(dt1))
		dt1 = SetDateTime(dt1);
	if (DATETIME_IS_RELATIVE(dt2))
		dt2 = SetDateTime(dt2);

	if (DATETIME_IS_INVALID(dt1)
		|| DATETIME_IS_INVALID(dt2))
	{
		DATETIME_INVALID(result->time);
1140

1141
	}
1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163
	else if ((datetime2tm(dt1, NULL, tm1, &fsec1, NULL) == 0)
			 && (datetime2tm(dt2, NULL, tm2, &fsec2, NULL) == 0))
	{
		fsec = (fsec1 - fsec2);
		tm->tm_sec = (tm1->tm_sec - tm2->tm_sec);
		tm->tm_min = (tm1->tm_min - tm2->tm_min);
		tm->tm_hour = (tm1->tm_hour - tm2->tm_hour);
		tm->tm_mday = (tm1->tm_mday - tm2->tm_mday);
		tm->tm_mon = (tm1->tm_mon - tm2->tm_mon);
		tm->tm_year = (tm1->tm_year - tm2->tm_year);

		/* flip sign if necessary... */
		if (dt1 < dt2)
		{
			fsec = -fsec;
			tm->tm_sec = -tm->tm_sec;
			tm->tm_min = -tm->tm_min;
			tm->tm_hour = -tm->tm_hour;
			tm->tm_mday = -tm->tm_mday;
			tm->tm_mon = -tm->tm_mon;
			tm->tm_year = -tm->tm_year;
		}
1164

1165 1166 1167 1168 1169
		if (tm->tm_sec < 0)
		{
			tm->tm_sec += 60;
			tm->tm_min--;
		}
1170

1171 1172 1173 1174 1175
		if (tm->tm_min < 0)
		{
			tm->tm_min += 60;
			tm->tm_hour--;
		}
1176

1177 1178 1179 1180 1181
		if (tm->tm_hour < 0)
		{
			tm->tm_hour += 24;
			tm->tm_mday--;
		}
1182

1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199
		if (tm->tm_mday < 0)
		{
			if (dt1 < dt2)
			{
				tm->tm_mday += mdays[tm1->tm_mon - 1];
				if (isleap(tm1->tm_year) && (tm1->tm_mon == 2))
					tm->tm_mday++;
				tm->tm_mon--;
			}
			else
			{
				tm->tm_mday += mdays[tm2->tm_mon - 1];
				if (isleap(tm2->tm_year) && (tm2->tm_mon == 2))
					tm->tm_mday++;
				tm->tm_mon--;
			}
		}
1200

1201 1202 1203 1204 1205
		if (tm->tm_mon < 0)
		{
			tm->tm_mon += 12;
			tm->tm_year--;
		}
1206

1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217
		/* recover sign if necessary... */
		if (dt1 < dt2)
		{
			fsec = -fsec;
			tm->tm_sec = -tm->tm_sec;
			tm->tm_min = -tm->tm_min;
			tm->tm_hour = -tm->tm_hour;
			tm->tm_mday = -tm->tm_mday;
			tm->tm_mon = -tm->tm_mon;
			tm->tm_year = -tm->tm_year;
		}
1218

1219
		if (tm2timespan(tm, fsec, result) != 0)
1220
			elog(ERROR, "Unable to decode datetime", NULL);
1221

1222 1223
	}
	else
1224
		elog(ERROR, "Unable to decode datetime", NULL);
1225

1226
	return result;
1227
}	/* datetime_age() */
1228 1229


1230
/*----------------------------------------------------------
1231
 *	Conversion operators.
1232 1233 1234
 *---------------------------------------------------------*/


1235 1236 1237
/* datetime_text()
 * Convert datetime to text data type.
 */
1238
text *
1239
datetime_text(DateTime *datetime)
1240
{
1241 1242 1243
	text	   *result;
	char	   *str;
	int			len;
1244

1245 1246
	if (!PointerIsValid(datetime))
		return NULL;
1247

1248
	str = datetime_out(datetime);
1249

1250 1251
	if (!PointerIsValid(str))
		return NULL;
1252

1253
	len = (strlen(str) + VARHDRSZ);
1254

1255
	result = palloc(len);
1256

1257 1258
	VARSIZE(result) = len;
	memmove(VARDATA(result), str, (len - VARHDRSZ));
1259

1260
	pfree(str);
1261

1262
	return result;
1263
}	/* datetime_text() */
1264 1265 1266 1267 1268


/* text_datetime()
 * Convert text string to datetime.
 * Text type is not null terminated, so use temporary string
1269
 *	then call the standard input routine.
1270
 */
1271
DateTime   *
1272
text_datetime(text *str)
1273
{
1274 1275 1276 1277 1278
	DateTime   *result;
	int			i;
	char	   *sp,
			   *dp,
				dstr[MAXDATELEN + 1];
1279

1280 1281
	if (!PointerIsValid(str))
		return NULL;
1282

1283 1284 1285 1286 1287
	sp = VARDATA(str);
	dp = dstr;
	for (i = 0; i < (VARSIZE(str) - VARHDRSZ); i++)
		*dp++ = *sp++;
	*dp = '\0';
1288

1289
	result = datetime_in(dstr);
1290

1291
	return result;
1292
}	/* text_datetime() */
1293 1294 1295 1296 1297


/* timespan_text()
 * Convert timespan to text data type.
 */
1298
text *
1299
timespan_text(TimeSpan *timespan)
1300
{
1301 1302 1303
	text	   *result;
	char	   *str;
	int			len;
1304

1305 1306
	if (!PointerIsValid(timespan))
		return NULL;
1307

1308
	str = timespan_out(timespan);
1309

1310 1311
	if (!PointerIsValid(str))
		return NULL;
1312

1313
	len = (strlen(str) + VARHDRSZ);
1314

1315
	result = palloc(len);
1316

1317 1318
	VARSIZE(result) = len;
	memmove(VARDATA(result), str, (len - VARHDRSZ));
1319

1320
	pfree(str);
1321

1322
	return result;
1323
}	/* timespan_text() */
1324 1325 1326 1327 1328


/* text_timespan()
 * Convert text string to timespan.
 * Text type may not be null terminated, so copy to temporary string
1329
 *	then call the standard input routine.
1330
 */
1331
TimeSpan   *
1332
text_timespan(text *str)
1333
{
1334 1335 1336 1337 1338
	TimeSpan   *result;
	int			i;
	char	   *sp,
			   *dp,
				dstr[MAXDATELEN + 1];
1339

1340 1341 1342 1343 1344 1345 1346 1347
	if (!PointerIsValid(str))
		return NULL;

	sp = VARDATA(str);
	dp = dstr;
	for (i = 0; i < (VARSIZE(str) - VARHDRSZ); i++)
		*dp++ = *sp++;
	*dp = '\0';
1348

1349
	result = timespan_in(dstr);
1350

1351
	return result;
1352
}	/* text_timespan() */
1353

1354 1355 1356
/* datetime_trunc()
 * Extract specified field from datetime.
 */
1357
DateTime   *
1358
datetime_trunc(text *units, DateTime *datetime)
1359
{
1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373
	DateTime   *result;

	DateTime	dt;
	int			tz;
	int			type,
				val;
	int			i;
	char	   *up,
			   *lp,
				lowunits[MAXDATELEN + 1];
	double		fsec;
	char	   *tzn;
	struct tm	tt,
			   *tm = &tt;
1374 1375 1376 1377

	if ((!PointerIsValid(units)) || (!PointerIsValid(datetime)))
		return NULL;

1378
	result = palloc(sizeof(DateTime));
1379 1380 1381 1382 1383 1384 1385 1386

	up = VARDATA(units);
	lp = lowunits;
	for (i = 0; i < (VARSIZE(units) - VARHDRSZ); i++)
		*lp++ = tolower(*up++);
	*lp = '\0';

	type = DecodeUnits(0, lowunits, &val);
1387 1388

#ifdef DATEDEBUG
1389 1390 1391
	if (type == IGNORE)
		strcpy(lowunits, "(unknown)");
	printf("datetime_trunc- units %s type=%d value=%d\n", lowunits, type, val);
1392 1393
#endif

1394 1395
	if (DATETIME_NOT_FINITE(*datetime))
	{
1396 1397
#if FALSE
/* should return null but Postgres doesn't like that currently. - tgl 97/06/12 */
1398
		elog(ERROR, "Datetime is not finite", NULL);
1399 1400
#endif
		*result = 0;
1401

1402 1403 1404 1405 1406 1407 1408 1409 1410
	}
	else
	{
		dt = (DATETIME_IS_RELATIVE(*datetime) ? SetDateTime(*datetime) : *datetime);

		if ((type == UNITS) && (datetime2tm(dt, &tz, tm, &fsec, &tzn) == 0))
		{
			switch (val)
			{
1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431
				case DTK_MILLENIUM:
					tm->tm_year = (tm->tm_year / 1000) * 1000;
				case DTK_CENTURY:
					tm->tm_year = (tm->tm_year / 100) * 100;
				case DTK_DECADE:
					tm->tm_year = (tm->tm_year / 10) * 10;
				case DTK_YEAR:
					tm->tm_mon = 1;
				case DTK_QUARTER:
					tm->tm_mon = (3 * (tm->tm_mon / 4)) + 1;
				case DTK_MONTH:
					tm->tm_mday = 1;
				case DTK_DAY:
					tm->tm_hour = 0;
				case DTK_HOUR:
					tm->tm_min = 0;
				case DTK_MINUTE:
					tm->tm_sec = 0;
				case DTK_SECOND:
					fsec = 0;
					break;
1432

1433 1434 1435
				case DTK_MILLISEC:
					fsec = rint(fsec * 1000) / 1000;
					break;
1436

1437 1438 1439
				case DTK_MICROSEC:
					fsec = rint(fsec * 1000) / 1000;
					break;
1440

1441
				default:
1442
					elog(ERROR, "Datetime units '%s' not supported", lowunits);
1443
					result = NULL;
1444 1445 1446 1447
			}

			if (IS_VALID_UTIME(tm->tm_year, tm->tm_mon, tm->tm_mday))
			{
1448
#ifdef USE_POSIX_TIME
1449 1450 1451 1452 1453 1454 1455
				tm->tm_isdst = -1;
				tm->tm_year -= 1900;
				tm->tm_mon -= 1;
				tm->tm_isdst = -1;
				mktime(tm);
				tm->tm_year += 1900;
				tm->tm_mon += 1;
1456

1457
#if defined(HAVE_TM_ZONE)
1458
				tz = -(tm->tm_gmtoff);	/* tm_gmtoff is Sun/DEC-ism */
1459 1460 1461 1462
#elif defined(HAVE_INT_TIMEZONE)
				tz = ((tm->tm_isdst > 0) ? (timezone - 3600) : timezone);
#else
#error USE_POSIX_TIME is defined but neither HAVE_TM_ZONE or HAVE_INT_TIMEZONE are defined
1463 1464
#endif

1465 1466
#else							/* !USE_POSIX_TIME */
				tz = CTimeZone;
1467
#endif
1468 1469 1470 1471 1472 1473
			}
			else
			{
				tm->tm_isdst = 0;
				tz = 0;
			}
1474

1475
			if (tm2datetime(tm, fsec, &tz, result) != 0)
1476
				elog(ERROR, "Unable to truncate datetime to '%s'", lowunits);
1477 1478

#if FALSE
1479 1480 1481 1482 1483
		}
		else if ((type == RESERV) && (val == DTK_EPOCH))
		{
			DATETIME_EPOCH(*result);
			*result = dt - SetDateTime(*result);
1484 1485
#endif

1486 1487 1488
		}
		else
		{
1489
			elog(ERROR, "Datetime units '%s' not recognized", lowunits);
1490 1491
			result = NULL;
		}
1492
	}
1493

1494
	return result;
1495
}	/* datetime_trunc() */
1496 1497 1498 1499

/* timespan_trunc()
 * Extract specified field from timespan.
 */
1500
TimeSpan   *
1501
timespan_trunc(text *units, TimeSpan *timespan)
1502
{
1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513
	TimeSpan   *result;

	int			type,
				val;
	int			i;
	char	   *up,
			   *lp,
				lowunits[MAXDATELEN + 1];
	double		fsec;
	struct tm	tt,
			   *tm = &tt;
1514 1515 1516 1517

	if ((!PointerIsValid(units)) || (!PointerIsValid(timespan)))
		return NULL;

1518
	result = palloc(sizeof(TimeSpan));
1519 1520 1521 1522 1523 1524 1525 1526

	up = VARDATA(units);
	lp = lowunits;
	for (i = 0; i < (VARSIZE(units) - VARHDRSZ); i++)
		*lp++ = tolower(*up++);
	*lp = '\0';

	type = DecodeUnits(0, lowunits, &val);
1527 1528

#ifdef DATEDEBUG
1529 1530 1531
	if (type == IGNORE)
		strcpy(lowunits, "(unknown)");
	printf("timespan_trunc- units %s type=%d value=%d\n", lowunits, type, val);
1532 1533
#endif

1534 1535
	if (TIMESPAN_IS_INVALID(*timespan))
	{
1536
#if FALSE
1537
		elog(ERROR, "Timespan is not finite", NULL);
1538 1539 1540
#endif
		result = NULL;

1541
	}
1542 1543 1544 1545 1546 1547 1548
	else if (type == UNITS)
	{

		if (timespan2tm(*timespan, tm, &fsec) == 0)
		{
			switch (val)
			{
1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569
				case DTK_MILLENIUM:
					tm->tm_year = (tm->tm_year / 1000) * 1000;
				case DTK_CENTURY:
					tm->tm_year = (tm->tm_year / 100) * 100;
				case DTK_DECADE:
					tm->tm_year = (tm->tm_year / 10) * 10;
				case DTK_YEAR:
					tm->tm_mon = 0;
				case DTK_QUARTER:
					tm->tm_mon = (3 * (tm->tm_mon / 4));
				case DTK_MONTH:
					tm->tm_mday = 0;
				case DTK_DAY:
					tm->tm_hour = 0;
				case DTK_HOUR:
					tm->tm_min = 0;
				case DTK_MINUTE:
					tm->tm_sec = 0;
				case DTK_SECOND:
					fsec = 0;
					break;
1570

1571 1572 1573
				case DTK_MILLISEC:
					fsec = rint(fsec * 1000) / 1000;
					break;
1574

1575 1576 1577
				case DTK_MICROSEC:
					fsec = rint(fsec * 1000) / 1000;
					break;
1578

1579
				default:
1580
					elog(ERROR, "Timespan units '%s' not supported", lowunits);
1581
					result = NULL;
1582 1583 1584
			}

			if (tm2timespan(tm, fsec, result) != 0)
1585
				elog(ERROR, "Unable to truncate timespan to '%s'", lowunits);
1586 1587 1588 1589 1590 1591 1592

		}
		else
		{
			elog(NOTICE, "Timespan out of range", NULL);
			result = NULL;
		}
1593 1594

#if FALSE
1595
	}
1596 1597 1598 1599 1600 1601 1602 1603
	else if ((type == RESERV) && (val == DTK_EPOCH))
	{
		*result = timespan->time;
		if (timespan->month != 0)
		{
			*result += ((365.25 * 86400) * (timespan->month / 12));
			*result += ((30 * 86400) * (timespan->month % 12));
		}
1604 1605
#endif

1606 1607 1608
	}
	else
	{
1609
		elog(ERROR, "Timespan units '%s' not recognized", units);
1610 1611
		result = NULL;
	}
1612

1613
	return result;
1614
}	/* timespan_trunc() */
1615 1616


1617 1618 1619
/* datetime_part()
 * Extract specified field from datetime.
 */
1620
float64
1621
datetime_part(text *units, DateTime *datetime)
1622
{
1623 1624 1625 1626 1627 1628 1629 1630 1631 1632
	float64		result;

	DateTime	dt;
	int			tz;
	int			type,
				val;
	int			i;
	char	   *up,
			   *lp,
				lowunits[MAXDATELEN + 1];
1633
	double		dummy;
1634 1635 1636 1637
	double		fsec;
	char	   *tzn;
	struct tm	tt,
			   *tm = &tt;
1638 1639 1640 1641

	if ((!PointerIsValid(units)) || (!PointerIsValid(datetime)))
		return NULL;

1642
	result = palloc(sizeof(float64data));
1643 1644 1645 1646 1647 1648 1649 1650 1651 1652

	up = VARDATA(units);
	lp = lowunits;
	for (i = 0; i < (VARSIZE(units) - VARHDRSZ); i++)
		*lp++ = tolower(*up++);
	*lp = '\0';

	type = DecodeUnits(0, lowunits, &val);
	if (type == IGNORE)
		type = DecodeSpecial(0, lowunits, &val);
1653 1654

#ifdef DATEDEBUG
1655 1656 1657
	if (type == IGNORE)
		strcpy(lowunits, "(unknown)");
	printf("datetime_part- units %s type=%d value=%d\n", lowunits, type, val);
1658 1659
#endif

1660 1661
	if (DATETIME_NOT_FINITE(*datetime))
	{
1662
#if FALSE
1663
/* should return null but Postgres doesn't like that currently. - tgl 97/06/12 */
1664
		elog(ERROR, "Datetime is not finite", NULL);
1665
#endif
1666
		*result = 0;
1667

1668 1669 1670 1671 1672 1673 1674 1675 1676
	}
	else
	{
		dt = (DATETIME_IS_RELATIVE(*datetime) ? SetDateTime(*datetime) : *datetime);

		if ((type == UNITS) && (datetime2tm(dt, &tz, tm, &fsec, &tzn) == 0))
		{
			switch (val)
			{
1677 1678 1679
				case DTK_TZ:
					*result = tz;
					break;
1680

1681 1682 1683 1684 1685 1686 1687 1688 1689 1690
				case DTK_TZ_MINUTE:
					*result = tz / 60;
					TMODULO(*result, dummy, 60e0);
					break;

				case DTK_TZ_HOUR:
					dummy = tz;
					TMODULO(dummy, *result, 3600e0);
					break;

1691 1692 1693
				case DTK_MICROSEC:
					*result = (fsec * 1000000);
					break;
1694

1695 1696 1697
				case DTK_MILLISEC:
					*result = (fsec * 1000);
					break;
1698

1699 1700 1701
				case DTK_SECOND:
					*result = (tm->tm_sec + fsec);
					break;
1702

1703 1704 1705
				case DTK_MINUTE:
					*result = tm->tm_min;
					break;
1706

1707 1708 1709
				case DTK_HOUR:
					*result = tm->tm_hour;
					break;
1710

1711 1712 1713
				case DTK_DAY:
					*result = tm->tm_mday;
					break;
1714

1715 1716 1717
				case DTK_MONTH:
					*result = tm->tm_mon;
					break;
1718

1719 1720 1721
				case DTK_QUARTER:
					*result = (tm->tm_mon / 4) + 1;
					break;
1722

1723 1724 1725
				case DTK_YEAR:
					*result = tm->tm_year;
					break;
1726

1727 1728 1729
				case DTK_DECADE:
					*result = (tm->tm_year / 10) + 1;
					break;
1730

1731 1732 1733
				case DTK_CENTURY:
					*result = (tm->tm_year / 100) + 1;
					break;
1734

1735 1736 1737
				case DTK_MILLENIUM:
					*result = (tm->tm_year / 1000) + 1;
					break;
1738

1739
				default:
1740
					elog(ERROR, "Datetime units '%s' not supported", lowunits);
1741
					*result = 0;
1742
			}
1743

1744 1745 1746 1747 1748
		}
		else if (type == RESERV)
		{
			switch (val)
			{
1749 1750 1751 1752
				case DTK_EPOCH:
					DATETIME_EPOCH(*result);
					*result = dt - SetDateTime(*result);
					break;
1753

1754 1755
				case DTK_DOW:
					if (datetime2tm(dt, &tz, tm, &fsec, &tzn) != 0)
1756
						elog(ERROR, "Unable to encode datetime", NULL);
1757

1758 1759
					*result = j2day(date2j(tm->tm_year, tm->tm_mon, tm->tm_mday));
					break;
1760

1761 1762
				case DTK_DOY:
					if (datetime2tm(dt, &tz, tm, &fsec, &tzn) != 0)
1763
						elog(ERROR, "Unable to encode datetime", NULL);
1764 1765

					*result = (date2j(tm->tm_year, tm->tm_mon, tm->tm_mday)
1766
							   - date2j(tm->tm_year, 1, 1) + 1);
1767 1768
					break;

1769
				default:
1770
					elog(ERROR, "Datetime units '%s' not supported", lowunits);
1771
					*result = 0;
1772
			}
1773

1774 1775 1776
		}
		else
		{
1777
			elog(ERROR, "Datetime units '%s' not recognized", lowunits);
1778 1779 1780
			*result = 0;
		}
	}
1781

1782
	return result;
1783
}	/* datetime_part() */
1784 1785


1786 1787 1788 1789
/* timespan_part()
 * Extract specified field from timespan.
 */
float64
1790
timespan_part(text *units, TimeSpan *timespan)
1791
{
1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802
	float64		result;

	int			type,
				val;
	int			i;
	char	   *up,
			   *lp,
				lowunits[MAXDATELEN + 1];
	double		fsec;
	struct tm	tt,
			   *tm = &tt;
1803 1804 1805 1806

	if ((!PointerIsValid(units)) || (!PointerIsValid(timespan)))
		return NULL;

1807
	result = palloc(sizeof(float64data));
1808 1809 1810 1811 1812 1813 1814 1815 1816 1817

	up = VARDATA(units);
	lp = lowunits;
	for (i = 0; i < (VARSIZE(units) - VARHDRSZ); i++)
		*lp++ = tolower(*up++);
	*lp = '\0';

	type = DecodeUnits(0, lowunits, &val);
	if (type == IGNORE)
		type = DecodeSpecial(0, lowunits, &val);
1818

1819 1820 1821 1822 1823
#ifdef DATEDEBUG
	if (type == IGNORE)
		strcpy(lowunits, "(unknown)");
	printf("timespan_part- units %s type=%d value=%d\n", lowunits, type, val);
#endif
1824

1825 1826 1827
	if (TIMESPAN_IS_INVALID(*timespan))
	{
#if FALSE
1828
		elog(ERROR, "Timespan is not finite", NULL);
1829
#endif
1830 1831
		*result = 0;

1832 1833 1834 1835 1836 1837 1838 1839
	}
	else if (type == UNITS)
	{

		if (timespan2tm(*timespan, tm, &fsec) == 0)
		{
			switch (val)
			{
1840 1841 1842
				case DTK_MICROSEC:
					*result = (fsec * 1000000);
					break;
1843

1844 1845 1846
				case DTK_MILLISEC:
					*result = (fsec * 1000);
					break;
1847

1848 1849 1850
				case DTK_SECOND:
					*result = (tm->tm_sec + fsec);
					break;
1851

1852 1853 1854
				case DTK_MINUTE:
					*result = tm->tm_min;
					break;
1855

1856 1857 1858
				case DTK_HOUR:
					*result = tm->tm_hour;
					break;
1859

1860 1861 1862
				case DTK_DAY:
					*result = tm->tm_mday;
					break;
1863

1864 1865 1866
				case DTK_MONTH:
					*result = tm->tm_mon;
					break;
1867

1868 1869 1870
				case DTK_QUARTER:
					*result = (tm->tm_mon / 4) + 1;
					break;
1871

1872 1873 1874
				case DTK_YEAR:
					*result = tm->tm_year;
					break;
1875

1876 1877 1878
				case DTK_DECADE:
					*result = (tm->tm_year / 10) + 1;
					break;
1879

1880 1881 1882
				case DTK_CENTURY:
					*result = (tm->tm_year / 100) + 1;
					break;
1883

1884 1885 1886
				case DTK_MILLENIUM:
					*result = (tm->tm_year / 1000) + 1;
					break;
1887

1888
				default:
1889
					elog(ERROR, "Timespan units '%s' not yet supported", units);
1890
					result = NULL;
1891
			}
1892

1893 1894 1895 1896 1897 1898
		}
		else
		{
			elog(NOTICE, "Timespan out of range", NULL);
			*result = 0;
		}
1899

1900 1901 1902 1903 1904 1905 1906 1907 1908
	}
	else if ((type == RESERV) && (val == DTK_EPOCH))
	{
		*result = timespan->time;
		if (timespan->month != 0)
		{
			*result += ((365.25 * 86400) * (timespan->month / 12));
			*result += ((30 * 86400) * (timespan->month % 12));
		}
1909

1910 1911 1912
	}
	else
	{
1913
		elog(ERROR, "Timespan units '%s' not recognized", units);
1914
		*result = 0;
1915
	}
1916

1917
	return result;
1918
}	/* timespan_part() */
1919 1920


1921 1922
/* datetime_zone()
 * Encode datetime type with specified time zone.
1923
 */
1924
text *
1925
datetime_zone(text *zone, DateTime *datetime)
1926
{
1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943
	text	   *result;

	DateTime	dt;
	int			tz;
	int			type,
				val;
	int			i;
	char	   *up,
			   *lp,
				lowzone[MAXDATELEN + 1];
	char	   *tzn,
				upzone[MAXDATELEN + 1];
	double		fsec;
	struct tm	tt,
			   *tm = &tt;
	char		buf[MAXDATELEN + 1];
	int			len;
1944 1945 1946 1947 1948 1949 1950 1951 1952

	if ((!PointerIsValid(zone)) || (!PointerIsValid(datetime)))
		return NULL;

	up = VARDATA(zone);
	lp = lowzone;
	for (i = 0; i < (VARSIZE(zone) - VARHDRSZ); i++)
		*lp++ = tolower(*up++);
	*lp = '\0';
1953

1954
	type = DecodeSpecial(0, lowzone, &val);
1955 1956

#ifdef DATEDEBUG
1957 1958 1959
	if (type == IGNORE)
		strcpy(lowzone, "(unknown)");
	printf("datetime_zone- zone %s type=%d value=%d\n", lowzone, type, val);
1960 1961
#endif

1962 1963
	if (DATETIME_NOT_FINITE(*datetime))
	{
1964

1965 1966 1967 1968
		/*
		 * could return null but Postgres doesn't like that currently. -
		 * tgl 97/06/12
		 */
1969
		elog(ERROR, "Datetime is not finite", NULL);
1970
		result = NULL;
1971

1972 1973 1974 1975 1976
	}
	else if ((type == TZ) || (type == DTZ))
	{
		tm->tm_isdst = ((type == DTZ) ? 1 : 0);
		tz = val * 60;
1977

1978 1979
		dt = (DATETIME_IS_RELATIVE(*datetime) ? SetDateTime(*datetime) : *datetime);
		dt = dt2local(dt, tz);
1980

1981
		if (datetime2tm(dt, NULL, tm, &fsec, NULL) != 0)
1982
			elog(ERROR, "Datetime not legal", NULL);
1983

1984 1985 1986 1987 1988
		up = upzone;
		lp = lowzone;
		for (i = 0; *lp != '\0'; i++)
			*up++ = toupper(*lp++);
		*up = '\0';
1989

1990 1991
		tzn = upzone;
		EncodeDateTime(tm, fsec, &tz, &tzn, DateStyle, buf);
1992

1993
		len = (strlen(buf) + VARHDRSZ);
1994

1995
		result = palloc(len);
1996

1997 1998
		VARSIZE(result) = len;
		memmove(VARDATA(result), buf, (len - VARHDRSZ));
1999

2000
	}
2001 2002
	else
	{
2003
		elog(ERROR, "Time zone '%s' not recognized", lowzone);
2004
		result = NULL;
2005
	}
2006

2007
	return result;
2008
}	/* datetime_zone() */
2009 2010


2011 2012
/*****************************************************************************
 *	 PRIVATE ROUTINES														 *
2013
 *****************************************************************************/
2014 2015

/* definitions for squeezing values into "value" */
2016 2017 2018
#define ABS_SIGNBIT		(char) 0200
#define VALMASK			(char) 0177
#define NEG(n)			((n)|ABS_SIGNBIT)
2019
#define SIGNEDCHAR(c)	((c)&ABS_SIGNBIT? -((c)&VALMASK): (c))
2020
#define FROMVAL(tp)		(-SIGNEDCHAR((tp)->value) * 10) /* uncompress */
2021 2022 2023 2024 2025 2026 2027
#define TOVAL(tp, v)	((tp)->value = ((v) < 0? NEG((-(v))/10): (v)/10))

/*
 * to keep this table reasonably small, we divide the lexval for TZ and DTZ
 * entries by 10 and truncate the text field at MAXTOKLEN characters.
 * the text field is not guaranteed to be NULL-terminated.
 */
2028
static datetkn datetktbl[] = {
2029
/*		text			token	lexval */
2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072
	{EARLY, RESERV, DTK_EARLY}, /* "-infinity" reserved for "early time" */
	{"acsst", DTZ, 63},			/* Cent. Australia */
	{"acst", TZ, 57},			/* Cent. Australia */
	{DA_D, ADBC, AD},			/* "ad" for years >= 0 */
	{"abstime", IGNORE, 0},		/* "abstime" for pre-v6.1 "Invalid
								 * Abstime" */
	{"adt", DTZ, NEG(18)},		/* Atlantic Daylight Time */
	{"aesst", DTZ, 66},			/* E. Australia */
	{"aest", TZ, 60},			/* Australia Eastern Std Time */
	{"ahst", TZ, 60},			/* Alaska-Hawaii Std Time */
	{"allballs", RESERV, DTK_ZULU},		/* 00:00:00 */
	{"am", AMPM, AM},
	{"apr", MONTH, 4},
	{"april", MONTH, 4},
	{"ast", TZ, NEG(24)},		/* Atlantic Std Time (Canada) */
	{"at", IGNORE, 0},			/* "at" (throwaway) */
	{"aug", MONTH, 8},
	{"august", MONTH, 8},
	{"awsst", DTZ, 54},			/* W. Australia */
	{"awst", TZ, 48},			/* W. Australia */
	{DB_C, ADBC, BC},			/* "bc" for years < 0 */
	{"bst", TZ, 6},				/* British Summer Time */
	{"bt", TZ, 18},				/* Baghdad Time */
	{"cadt", DTZ, 63},			/* Central Australian DST */
	{"cast", TZ, 57},			/* Central Australian ST */
	{"cat", TZ, NEG(60)},		/* Central Alaska Time */
	{"cct", TZ, 48},			/* China Coast */
	{"cdt", DTZ, NEG(30)},		/* Central Daylight Time */
	{"cet", TZ, 6},				/* Central European Time */
	{"cetdst", DTZ, 12},		/* Central European Dayl.Time */
	{"cst", TZ, NEG(36)},		/* Central Standard Time */
	{DCURRENT, RESERV, DTK_CURRENT},	/* "current" is always now */
	{"dec", MONTH, 12},
	{"december", MONTH, 12},
	{"dnt", TZ, 6},				/* Dansk Normal Tid */
	{"dow", RESERV, DTK_DOW},	/* day of week */
	{"doy", RESERV, DTK_DOY},	/* day of year */
	{"dst", DTZMOD, 6},
	{"east", TZ, NEG(60)},		/* East Australian Std Time */
	{"edt", DTZ, NEG(24)},		/* Eastern Daylight Time */
	{"eet", TZ, 12},			/* East. Europe, USSR Zone 1 */
	{"eetdst", DTZ, 18},		/* Eastern Europe */
	{EPOCH, RESERV, DTK_EPOCH}, /* "epoch" reserved for system epoch time */
2073
#if USE_AUSTRALIAN_RULES
2074
	{"est", TZ, 60},			/* Australia Eastern Std Time */
2075
#else
2076
	{"est", TZ, NEG(30)},		/* Eastern Standard Time */
2077
#endif
2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178
	{"feb", MONTH, 2},
	{"february", MONTH, 2},
	{"fri", DOW, 5},
	{"friday", DOW, 5},
	{"fst", TZ, 6},				/* French Summer Time */
	{"fwt", DTZ, 12},			/* French Winter Time  */
	{"gmt", TZ, 0},				/* Greenwish Mean Time */
	{"gst", TZ, 60},			/* Guam Std Time, USSR Zone 9 */
	{"hdt", DTZ, NEG(54)},		/* Hawaii/Alaska */
	{"hmt", DTZ, 18},			/* Hellas ? ? */
	{"hst", TZ, NEG(60)},		/* Hawaii Std Time */
	{"idle", TZ, 72},			/* Intl. Date Line, East */
	{"idlw", TZ, NEG(72)},		/* Intl. Date Line,,	est */
	{LATE, RESERV, DTK_LATE},	/* "infinity" reserved for "late time" */
	{INVALID, RESERV, DTK_INVALID},		/* "invalid" reserved for invalid
										 * time */
	{"ist", TZ, 12},			/* Israel */
	{"it", TZ, 22},				/* Iran Time */
	{"jan", MONTH, 1},
	{"january", MONTH, 1},
	{"jst", TZ, 54},			/* Japan Std Time,USSR Zone 8 */
	{"jt", TZ, 45},				/* Java Time */
	{"jul", MONTH, 7},
	{"july", MONTH, 7},
	{"jun", MONTH, 6},
	{"june", MONTH, 6},
	{"kst", TZ, 54},			/* Korea Standard Time */
	{"ligt", TZ, 60},			/* From Melbourne, Australia */
	{"mar", MONTH, 3},
	{"march", MONTH, 3},
	{"may", MONTH, 5},
	{"mdt", DTZ, NEG(36)},		/* Mountain Daylight Time */
	{"mest", DTZ, 12},			/* Middle Europe Summer Time */
	{"met", TZ, 6},				/* Middle Europe Time */
	{"metdst", DTZ, 12},		/* Middle Europe Daylight Time */
	{"mewt", TZ, 6},			/* Middle Europe Winter Time */
	{"mez", TZ, 6},				/* Middle Europe Zone */
	{"mon", DOW, 1},
	{"monday", DOW, 1},
	{"mst", TZ, NEG(42)},		/* Mountain Standard Time */
	{"mt", TZ, 51},				/* Moluccas Time */
	{"ndt", DTZ, NEG(15)},		/* Nfld. Daylight Time */
	{"nft", TZ, NEG(21)},		/* Newfoundland Standard Time */
	{"nor", TZ, 6},				/* Norway Standard Time */
	{"nov", MONTH, 11},
	{"november", MONTH, 11},
	{NOW, RESERV, DTK_NOW},		/* current transaction time */
	{"nst", TZ, NEG(21)},		/* Nfld. Standard Time */
	{"nt", TZ, NEG(66)},		/* Nome Time */
	{"nzdt", DTZ, 78},			/* New Zealand Daylight Time */
	{"nzst", TZ, 72},			/* New Zealand Standard Time */
	{"nzt", TZ, 72},			/* New Zealand Time */
	{"oct", MONTH, 10},
	{"october", MONTH, 10},
	{"on", IGNORE, 0},			/* "on" (throwaway) */
	{"pdt", DTZ, NEG(42)},		/* Pacific Daylight Time */
	{"pm", AMPM, PM},
	{"pst", TZ, NEG(48)},		/* Pacific Standard Time */
	{"sadt", DTZ, 63},			/* S. Australian Dayl. Time */
	{"sast", TZ, 57},			/* South Australian Std Time */
	{"sat", DOW, 6},
	{"saturday", DOW, 6},
	{"sep", MONTH, 9},
	{"sept", MONTH, 9},
	{"september", MONTH, 9},
	{"set", TZ, NEG(6)},		/* Seychelles Time ?? */
	{"sst", DTZ, 12},			/* Swedish Summer Time */
	{"sun", DOW, 0},
	{"sunday", DOW, 0},
	{"swt", TZ, 6},				/* Swedish Winter Time	*/
	{"thu", DOW, 4},
	{"thur", DOW, 4},
	{"thurs", DOW, 4},
	{"thursday", DOW, 4},
	{TODAY, RESERV, DTK_TODAY}, /* midnight */
	{TOMORROW, RESERV, DTK_TOMORROW},	/* tomorrow midnight */
	{"tue", DOW, 2},
	{"tues", DOW, 2},
	{"tuesday", DOW, 2},
	{"undefined", RESERV, DTK_INVALID}, /* "undefined" pre-v6.1 invalid
										 * time */
	{"ut", TZ, 0},
	{"utc", TZ, 0},
	{"wadt", DTZ, 48},			/* West Australian DST */
	{"wast", TZ, 42},			/* West Australian Std Time */
	{"wat", TZ, NEG(6)},		/* West Africa Time */
	{"wdt", DTZ, 54},			/* West Australian DST */
	{"wed", DOW, 3},
	{"wednesday", DOW, 3},
	{"weds", DOW, 3},
	{"wet", TZ, 0},				/* Western Europe */
	{"wetdst", DTZ, 6},			/* Western Europe */
	{"wst", TZ, 48},			/* West Australian Std Time */
	{"ydt", DTZ, NEG(48)},		/* Yukon Daylight Time */
	{YESTERDAY, RESERV, DTK_YESTERDAY}, /* yesterday midnight */
	{"yst", TZ, NEG(54)},		/* Yukon Standard Time */
	{"zp4", TZ, NEG(24)},		/* GMT +4  hours. */
	{"zp5", TZ, NEG(30)},		/* GMT +5  hours. */
	{"zp6", TZ, NEG(36)},		/* GMT +6  hours. */
	{"z", RESERV, DTK_ZULU},	/* 00:00:00 */
	{ZULU, RESERV, DTK_ZULU},	/* 00:00:00 */
Bruce Momjian's avatar
Bruce Momjian committed
2179
};
2180 2181 2182

static unsigned int szdatetktbl = sizeof datetktbl / sizeof datetktbl[0];

2183
static datetkn deltatktbl[] = {
2184
/*		text			token	lexval */
2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205
	{"@", IGNORE, 0},			/* postgres relative time prefix */
	{DAGO, AGO, 0},				/* "ago" indicates negative time offset */
	{"c", UNITS, DTK_CENTURY},	/* "century" relative time units */
	{"cent", UNITS, DTK_CENTURY},		/* "century" relative time units */
	{"centuries", UNITS, DTK_CENTURY},	/* "centuries" relative time units */
	{DCENTURY, UNITS, DTK_CENTURY},		/* "century" relative time units */
	{"d", UNITS, DTK_DAY},		/* "day" relative time units */
	{DDAY, UNITS, DTK_DAY},		/* "day" relative time units */
	{"days", UNITS, DTK_DAY},	/* "days" relative time units */
	{"dec", UNITS, DTK_DECADE}, /* "decade" relative time units */
	{"decs", UNITS, DTK_DECADE},/* "decades" relative time units */
	{DDECADE, UNITS, DTK_DECADE},		/* "decade" relative time units */
	{"decades", UNITS, DTK_DECADE},		/* "decades" relative time units */
	{"h", UNITS, DTK_HOUR},		/* "hour" relative time units */
	{DHOUR, UNITS, DTK_HOUR},	/* "hour" relative time units */
	{"hours", UNITS, DTK_HOUR}, /* "hours" relative time units */
	{"hr", UNITS, DTK_HOUR},	/* "hour" relative time units */
	{"hrs", UNITS, DTK_HOUR},	/* "hours" relative time units */
	{INVALID, RESERV, DTK_INVALID},		/* "invalid" reserved for invalid
										 * time */
	{"m", UNITS, DTK_MINUTE},	/* "minute" relative time units */
2206
	{"microsecon", UNITS, DTK_MICROSEC},		/* "microsecond" relative
2207 2208 2209 2210 2211
												 * time units */
	{"mil", UNITS, DTK_MILLENIUM},		/* "millenium" relative time units */
	{"mils", UNITS, DTK_MILLENIUM},		/* "millenia" relative time units */
	{"millenia", UNITS, DTK_MILLENIUM}, /* "millenia" relative time units */
	{DMILLENIUM, UNITS, DTK_MILLENIUM}, /* "millenium" relative time units */
2212
	{"millisecon", UNITS, DTK_MILLISEC},		/* relative time units */
2213 2214 2215 2216 2217 2218 2219 2220
	{"min", UNITS, DTK_MINUTE}, /* "minute" relative time units */
	{"mins", UNITS, DTK_MINUTE},/* "minutes" relative time units */
	{"mins", UNITS, DTK_MINUTE},/* "minutes" relative time units */
	{DMINUTE, UNITS, DTK_MINUTE},		/* "minute" relative time units */
	{"minutes", UNITS, DTK_MINUTE},		/* "minutes" relative time units */
	{"mon", UNITS, DTK_MONTH},	/* "months" relative time units */
	{"mons", UNITS, DTK_MONTH}, /* "months" relative time units */
	{DMONTH, UNITS, DTK_MONTH}, /* "month" relative time units */
2221 2222 2223 2224 2225 2226
	{"months", UNITS, DTK_MONTH},
	{"ms", UNITS, DTK_MILLISEC},
	{"msec", UNITS, DTK_MILLISEC},
	{DMILLISEC, UNITS, DTK_MILLISEC},
	{"mseconds", UNITS, DTK_MILLISEC},
	{"msecs", UNITS, DTK_MILLISEC},
2227
	{"qtr", UNITS, DTK_QUARTER},/* "quarter" relative time */
2228
	{DQUARTER, UNITS, DTK_QUARTER},		/* "quarter" relative time */
2229
	{"reltime", IGNORE, 0},		/* for pre-v6.1 "Undefined Reltime" */
2230 2231 2232 2233 2234
	{"s", UNITS, DTK_SECOND},
	{"sec", UNITS, DTK_SECOND},
	{DSECOND, UNITS, DTK_SECOND},
	{"seconds", UNITS, DTK_SECOND},
	{"secs", UNITS, DTK_SECOND},
2235 2236
	{DTIMEZONE, UNITS, DTK_TZ}, /* "timezone" time offset */
	{"tz", UNITS, DTK_TZ},		/* "timezone" time offset */
2237
	{"tz_hour", UNITS, DTK_TZ_HOUR},	/* timezone hour units */
2238
	{"tz_minute", UNITS, DTK_TZ_MINUTE},		/* timezone minutes units */
2239
	{"undefined", RESERV, DTK_INVALID}, /* pre-v6.1 invalid time */
2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256
	{"us", UNITS, DTK_MICROSEC},/* "microsecond" relative time units */
	{"usec", UNITS, DTK_MICROSEC},		/* "microsecond" relative time
										 * units */
	{DMICROSEC, UNITS, DTK_MICROSEC},	/* "microsecond" relative time
										 * units */
	{"useconds", UNITS, DTK_MICROSEC},	/* "microseconds" relative time
										 * units */
	{"usecs", UNITS, DTK_MICROSEC},		/* "microseconds" relative time
										 * units */
	{"w", UNITS, DTK_WEEK},		/* "week" relative time units */
	{DWEEK, UNITS, DTK_WEEK},	/* "week" relative time units */
	{"weeks", UNITS, DTK_WEEK}, /* "weeks" relative time units */
	{"y", UNITS, DTK_YEAR},		/* "year" relative time units */
	{DYEAR, UNITS, DTK_YEAR},	/* "year" relative time units */
	{"years", UNITS, DTK_YEAR}, /* "years" relative time units */
	{"yr", UNITS, DTK_YEAR},	/* "year" relative time units */
	{"yrs", UNITS, DTK_YEAR},	/* "years" relative time units */
Bruce Momjian's avatar
Bruce Momjian committed
2257
};
2258 2259 2260 2261

static unsigned int szdeltatktbl = sizeof deltatktbl / sizeof deltatktbl[0];

#if USE_DATE_CACHE
2262
datetkn    *datecache[MAXDATEFIELDS] = {NULL};
2263

2264
datetkn    *deltacache[MAXDATEFIELDS] = {NULL};
2265 2266 2267 2268 2269 2270 2271

#endif


/*
 * Calendar time to Julian date conversions.
 * Julian date is commonly used in astronomical applications,
2272
 *	since it is numerically accurate and computationally simple.
2273
 * The algorithms here will accurately convert between Julian day
2274 2275
 *	and calendar date for all non-negative Julian days
 *	(i.e. from Nov 23, -4713 on).
2276 2277
 *
 * Ref: Explanatory Supplement to the Astronomical Almanac, 1992.
2278
 *	University Science Books, 20 Edgehill Rd. Mill Valley CA 94941.
2279
 *
2280
 * Use the algorithm by Henry Fliegel, a former NASA/JPL colleague
2281
 *	now at Aerospace Corp. (hi, Henry!)
2282
 *
2283 2284 2285
 * These routines will be used by other date/time packages - tgl 97/02/25
 */

2286
/* Set the minimum year to one greater than the year of the first valid day
2287
 *	to avoid having to check year and day both. - tgl 97/05/08
2288 2289 2290 2291 2292 2293 2294 2295 2296
 */

#define JULIAN_MINYEAR (-4713)
#define JULIAN_MINMONTH (11)
#define JULIAN_MINDAY (23)

#define IS_VALID_JULIAN(y,m,d) ((y > JULIAN_MINYEAR) \
 || ((y == JULIAN_MINYEAR) && ((m > JULIAN_MINMONTH) \
  || ((m == JULIAN_MINMONTH) && (d >= JULIAN_MINDAY)))))
2297 2298 2299 2300

int
date2j(int y, int m, int d)
{
2301
	int			m12 = (m - 14) / 12;
2302

2303 2304
	return ((1461 * (y + 4800 + m12)) / 4 + (367 * (m - 2 - 12 * (m12))) / 12
			- (3 * ((y + 4900 + m12) / 100)) / 4 + d - 32075);
2305
}	/* date2j() */
2306

2307
void
2308
j2date(int jd, int *year, int *month, int *day)
2309
{
2310 2311 2312 2313
	int			j,
				y,
				m,
				d;
2314

2315 2316 2317
	int			i,
				l,
				n;
2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333

	l = jd + 68569;
	n = (4 * l) / 146097;
	l -= (146097 * n + 3) / 4;
	i = (4000 * (l + 1)) / 1461001;
	l += 31 - (1461 * i) / 4;
	j = (80 * l) / 2447;
	d = l - (2447 * j) / 80;
	l = j / 11;
	m = (j + 2) - (12 * l);
	y = 100 * (n - 49) + i + l;

	*year = y;
	*month = m;
	*day = d;
	return;
2334
}	/* j2date() */
2335

2336
static int
2337
j2day(int date)
2338
{
2339
	int			day;
2340

2341
	day = (date + 1) % 7;
2342

2343
	return day;
2344
}	/* j2day() */
2345

2346 2347 2348 2349 2350

/* datetime2tm()
 * Convert datetime data type to POSIX time structure.
 * Note that year is _not_ 1900-based, but is an explicit full value.
 * Also, month is one-based, _not_ zero-based.
2351
 * Returns:
2352 2353
 *	 0 on success
 *	-1 on out of range
2354 2355
 *
 * For dates within the system-supported time_t range, convert to the
2356
 *	local time zone. If out of this range, leave as GMT. - tgl 97/05/27
2357
 */
2358
int
2359
datetime2tm(DateTime dt, int *tzp, struct tm * tm, double *fsec, char **tzn)
2360
{
2361 2362 2363 2364 2365
	double		date,
				date0,
				time,
				sec;
	time_t		utime;
2366

2367
#ifdef USE_POSIX_TIME
2368
	struct tm  *tx;
2369

2370
#endif
2371

2372
	date0 = date2j(2000, 1, 1);
2373

2374 2375
	time = dt;
	TMODULO(time, date, 86400e0);
2376

2377 2378 2379 2380 2381
	if (time < 0)
	{
		time += 86400;
		date -= 1;
	}
2382

2383 2384 2385
	/* Julian day routine does not work for negative Julian days */
	if (date < -date0)
		return -1;
2386

2387 2388
	/* add offset to go from J2000 back to standard Julian date */
	date += date0;
2389 2390

#ifdef DATEDEBUG
2391
	printf("datetime2tm- date is %f (%f %f)\n", dt, date, time);
2392 2393
#endif

2394 2395
	j2date((int) date, &tm->tm_year, &tm->tm_mon, &tm->tm_mday);
	dt2time(time, &tm->tm_hour, &tm->tm_min, &sec);
2396 2397

#ifdef DATEDEBUG
2398 2399
	printf("datetime2tm- date is %d.%02d.%02d\n", tm->tm_year, tm->tm_mon, tm->tm_mday);
	printf("datetime2tm- time is %02d:%02d:%02.0f\n", tm->tm_hour, tm->tm_min, sec);
2400 2401
#endif

2402
	*fsec = JROUND(sec);
2403
	TMODULO(*fsec, tm->tm_sec, 1e0);
2404 2405

#ifdef DATEDEBUG
2406
	printf("datetime2tm- time is %02d:%02d:%02d %.7f\n", tm->tm_hour, tm->tm_min, tm->tm_sec, *fsec);
2407 2408
#endif

2409 2410 2411 2412 2413
	if (tzp != NULL)
	{
		if (IS_VALID_UTIME(tm->tm_year, tm->tm_mon, tm->tm_mday))
		{
			utime = (dt + (date0 - date2j(1970, 1, 1)) * 86400);
2414

2415
#ifdef USE_POSIX_TIME
2416
			tx = localtime(&utime);
2417
#ifdef DATEDEBUG
2418 2419 2420 2421 2422
#if defined(HAVE_TM_ZONE)
			printf("datetime2tm- (localtime) %d.%02d.%02d %02d:%02d:%02.0f %s dst=%d\n",
				   tx->tm_year, tx->tm_mon, tx->tm_mday, tx->tm_hour, tx->tm_min, sec,
				   tx->tm_zone, tx->tm_isdst);
#elif defined(HAVE_INT_TIMEZONE)
2423 2424 2425
			printf("datetime2tm- (localtime) %d.%02d.%02d %02d:%02d:%02.0f %s %s dst=%d\n",
				   tx->tm_year, tx->tm_mon, tx->tm_mday, tx->tm_hour, tx->tm_min, sec,
				   tzname[0], tzname[1], tx->tm_isdst);
2426
#else
2427
#error USE_POSIX_TIME is defined but neither HAVE_TM_ZONE or HAVE_INT_TIMEZONE are defined
2428
#endif
2429
#endif
2430 2431 2432 2433 2434
			tm->tm_year = tx->tm_year + 1900;
			tm->tm_mon = tx->tm_mon + 1;
			tm->tm_mday = tx->tm_mday;
			tm->tm_hour = tx->tm_hour;
			tm->tm_min = tx->tm_min;
2435 2436 2437
#if FALSE
/* XXX HACK
 * Argh! My Linux box puts in a 1 second offset for dates less than 1970
2438 2439
 *	but only if the seconds field was non-zero. So, don't copy the seconds
 *	field and instead carry forward from the original - tgl 97/06/18
2440
 * Note that GNU/Linux uses the standard freeware zic package as do
2441
 *	many other platforms so this may not be GNU/Linux/ix86-specific.
2442
 */
2443
			tm->tm_sec = tx->tm_sec;
2444
#endif
2445
			tm->tm_isdst = tx->tm_isdst;
2446

2447
#if defined(HAVE_TM_ZONE)
2448 2449
			tm->tm_gmtoff = tx->tm_gmtoff;
			tm->tm_zone = tx->tm_zone;
2450

2451 2452
			*tzp = -(tm->tm_gmtoff);	/* tm_gmtoff is Sun/DEC-ism */
			if (tzn != NULL)
2453 2454 2455 2456 2457 2458 2459
				*tzn = (char *)tm->tm_zone;
#elif defined(HAVE_INT_TIMEZONE)
			*tzp = (tm->tm_isdst ? (timezone - 3600) : timezone);
			if (tzn != NULL)
				*tzn = tzname[(tm->tm_isdst > 0)];
#else
#error USE_POSIX_TIME is defined but neither HAVE_TM_ZONE or HAVE_INT_TIMEZONE are defined
2460
#endif
2461

2462 2463 2464 2465
#else							/* !USE_POSIX_TIME */
			*tzp = CTimeZone;	/* V7 conventions; don't know timezone? */
			if (tzn != NULL)
				*tzn = CTZName;
2466
#endif
2467

2468 2469 2470 2471 2472 2473 2474 2475
		}
		else
		{
			*tzp = 0;
			tm->tm_isdst = 0;
			if (tzn != NULL)
				*tzn = NULL;
		}
2476

2477
		dt = dt2local(dt, *tzp);
2478

2479 2480 2481 2482 2483 2484 2485
	}
	else
	{
		tm->tm_isdst = 0;
		if (tzn != NULL)
			*tzn = NULL;
	}
2486 2487

#ifdef DATEDEBUG
2488 2489
	printf("datetime2tm- date is %d.%02d.%02d\n", tm->tm_year, tm->tm_mon, tm->tm_mday);
	printf("datetime2tm- time is %02d:%02d:%02d %.7f\n", tm->tm_hour, tm->tm_min, tm->tm_sec, *fsec);
2490
#endif
2491 2492

#ifdef DATEDEBUG
2493
#ifdef USE_POSIX_TIME
2494 2495 2496 2497
#if defined(HAVE_TM_ZONE)
	printf("datetime2tm- timezone is %s; offset is %d\n",
		   tm->tm_zone, ((tzp != NULL) ? *tzp : 0));
#elif defined(HAVE_INT_TIMEZONE)
2498 2499
	printf("datetime2tm- timezone is %s; offset is %d (%d); daylight is %d\n",
		   tzname[tm->tm_isdst != 0], ((tzp != NULL) ? *tzp : 0), CTimeZone, CDayLight);
2500
#endif
2501
#endif
2502 2503
#endif

2504
	return 0;
2505
}	/* datetime2tm() */
2506

2507

2508 2509
/* tm2datetime()
 * Convert a tm structure to a datetime data type.
2510 2511
 * Note that year is _not_ 1900-based, but is an explicit full value.
 * Also, month is one-based, _not_ zero-based.
2512
 */
2513
int
2514
tm2datetime(struct tm * tm, double fsec, int *tzp, DateTime *result)
2515
{
2516

2517 2518
	double		date,
				time;
2519

2520 2521
	/* Julian day routines are not correct for negative Julian days */
	if (!IS_VALID_JULIAN(tm->tm_year, tm->tm_mon, tm->tm_mday))
2522
		return -1;
2523

2524 2525 2526
	date = date2j(tm->tm_year, tm->tm_mon, tm->tm_mday) - date2j(2000, 1, 1);
	time = time2t(tm->tm_hour, tm->tm_min, (tm->tm_sec + fsec));
	*result = (date * 86400 + time);
2527
#ifdef DATEDEBUG
2528 2529
	printf("tm2datetime- date is %f (%f %f %d)\n", *result, date, time, (((tm->tm_hour * 60) + tm->tm_min) * 60 + tm->tm_sec));
	printf("tm2datetime- time is %f %02d:%02d:%02d %f\n", time, tm->tm_hour, tm->tm_min, tm->tm_sec, fsec);
2530
#endif
2531 2532
	if (tzp != NULL)
		*result = dt2local(*result, -(*tzp));
2533

2534
	return 0;
2535
}	/* tm2datetime() */
2536 2537


2538 2539 2540
/* timespan2tm()
 * Convert a timespan data type to a tm structure.
 */
2541
static int
2542
timespan2tm(TimeSpan span, struct tm * tm, float8 *fsec)
2543
{
2544
	double		time;
2545

2546 2547 2548 2549
	if (span.month != 0)
	{
		tm->tm_year = span.month / 12;
		tm->tm_mon = span.month % 12;
2550

2551 2552 2553 2554 2555 2556
	}
	else
	{
		tm->tm_year = 0;
		tm->tm_mon = 0;
	}
2557

2558
#ifdef ROUND_ALL
2559
	time = JROUND(span.time);
2560
#else
2561
	time = span.time;
2562
#endif
2563

2564 2565 2566
	TMODULO(time, tm->tm_mday, 86400e0);
	TMODULO(time, tm->tm_hour, 3600e0);
	TMODULO(time, tm->tm_min, 60e0);
2567
	TMODULO(time, tm->tm_sec, 1e0);
2568
	*fsec = time;
2569 2570

#ifdef DATEDEBUG
2571 2572
	printf("timespan2tm- %d %f = %04d-%02d-%02d %02d:%02d:%02d %.2f\n", span.month, span.time,
		   tm->tm_year, tm->tm_mon, tm->tm_mday, tm->tm_hour, tm->tm_min, tm->tm_sec, *fsec);
2573 2574
#endif

2575
	return 0;
2576
}	/* timespan2tm() */
2577

2578
static int
2579
tm2timespan(struct tm * tm, double fsec, TimeSpan *span)
2580
{
2581 2582 2583
	span->month = ((tm->tm_year * 12) + tm->tm_mon);
	span->time = ((((((tm->tm_mday * 24) + tm->tm_hour) * 60) + tm->tm_min) * 60) + tm->tm_sec);
	span->time = JROUND(span->time + fsec);
2584

2585
#ifdef DATEDEBUG
2586 2587
	printf("tm2timespan- %d %f = %04d-%02d-%02d %02d:%02d:%02d %.2f\n", span->month, span->time,
		   tm->tm_year, tm->tm_mon, tm->tm_mday, tm->tm_hour, tm->tm_min, tm->tm_sec, fsec);
2588
#endif
2589

2590
	return 0;
2591
}	/* tm2timespan() */
2592 2593


2594
static DateTime
2595
dt2local(DateTime dt, int tz)
2596
{
2597 2598
	dt -= tz;
	dt = JROUND(dt);
2599
	return dt;
2600
}	/* dt2local() */
2601

2602
static double
2603
time2t(const int hour, const int min, const double sec)
2604
{
2605
	return (((hour * 60) + min) * 60) + sec;
2606
}	/* time2t() */
2607

2608
static void
2609
dt2time(DateTime jd, int *hour, int *min, double *sec)
2610
{
2611
	double		time;
2612

2613
	time = jd;
2614

2615 2616 2617 2618 2619
	*hour = (time / 3600);
	time -= ((*hour) * 3600);
	*min = (time / 60);
	time -= ((*min) * 60);
	*sec = JROUND(time);
2620

2621
	return;
2622
}	/* dt2time() */
2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634


/*
 * parse and convert date in timestr (the normal interface)
 *
 * Returns the number of seconds since epoch (J2000)
 */

/* ParseDateTime()
 * Break string into tokens based on a date/time context.
 */
int
2635
ParseDateTime(char *timestr, char *lowstr,
2636
			  char **field, int *ftype, int maxfields, int *numfields)
2637
{
2638 2639 2640
	int			nf = 0;
	char	   *cp = timestr;
	char	   *lp = lowstr;
2641

2642 2643 2644 2645 2646 2647 2648 2649 2650
#ifdef DATEDEBUG
	printf("ParseDateTime- input string is %s\n", timestr);
#endif
	/* outer loop through fields */
	while (*cp != '\0')
	{
		field[nf] = lp;

		/* leading digit? then date or time */
2651
		if (isdigit(*cp) || (*cp == '.'))
2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663
		{
			*lp++ = *cp++;
			while (isdigit(*cp))
				*lp++ = *cp++;
			/* time field? */
			if (*cp == ':')
			{
				ftype[nf] = DTK_TIME;
				while (isdigit(*cp) || (*cp == ':') || (*cp == '.'))
					*lp++ = *cp++;

			}
2664
			/* date field? allow embedded text month */
2665 2666 2667 2668 2669 2670 2671
			else if ((*cp == '-') || (*cp == '/') || (*cp == '.'))
			{
				ftype[nf] = DTK_DATE;
				while (isalnum(*cp) || (*cp == '-') || (*cp == '/') || (*cp == '.'))
					*lp++ = tolower(*cp++);

			}
2672 2673 2674 2675 2676

			/*
			 * otherwise, number only and will determine year, month, or
			 * day later
			 */
2677 2678 2679 2680
			else
				ftype[nf] = DTK_NUMBER;

		}
2681 2682 2683 2684 2685

		/*
		 * text? then date string, month, day of week, special, or
		 * timezone
		 */
2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706
		else if (isalpha(*cp))
		{
			ftype[nf] = DTK_STRING;
			*lp++ = tolower(*cp++);
			while (isalpha(*cp))
				*lp++ = tolower(*cp++);

			/* full date string with leading text month? */
			if ((*cp == '-') || (*cp == '/') || (*cp == '.'))
			{
				ftype[nf] = DTK_DATE;
				while (isdigit(*cp) || (*cp == '-') || (*cp == '/') || (*cp == '.'))
					*lp++ = tolower(*cp++);
			}

			/* skip leading spaces */
		}
		else if (isspace(*cp))
		{
			cp++;
			continue;
2707

2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743
			/* sign? then special or numeric timezone */
		}
		else if ((*cp == '+') || (*cp == '-'))
		{
			*lp++ = *cp++;
			/* soak up leading whitespace */
			while (isspace(*cp))
				cp++;
			/* numeric timezone? */
			if (isdigit(*cp))
			{
				ftype[nf] = DTK_TZ;
				*lp++ = *cp++;
				while (isdigit(*cp) || (*cp == ':'))
					*lp++ = *cp++;

				/* special? */
			}
			else if (isalpha(*cp))
			{
				ftype[nf] = DTK_SPECIAL;
				*lp++ = tolower(*cp++);
				while (isalpha(*cp))
					*lp++ = tolower(*cp++);

				/* otherwise something wrong... */
			}
			else
				return -1;

			/* ignore punctuation but use as delimiter */
		}
		else if (ispunct(*cp))
		{
			cp++;
			continue;
2744

2745 2746 2747 2748 2749 2750 2751 2752 2753
		}
		else
			return -1;

		/* force in a delimiter */
		*lp++ = '\0';
		nf++;
		if (nf > MAXDATEFIELDS)
			return -1;
2754
#ifdef DATEDEBUG
2755
		printf("ParseDateTime- set field[%d] to %s type %d\n", (nf - 1), field[nf - 1], ftype[nf - 1]);
2756
#endif
2757
	}
2758

2759
	*numfields = nf;
2760

2761
	return 0;
2762
}	/* ParseDateTime() */
2763 2764 2765 2766 2767


/* DecodeDateTime()
 * Interpret previously parsed fields for general date and time.
 * Return 0 if full date, 1 if only time, and -1 if problems.
2768 2769 2770 2771 2772 2773 2774 2775 2776 2777
 *		External format(s):
 *				"<weekday> <month>-<day>-<year> <hour>:<minute>:<second>"
 *				"Fri Feb-7-1997 15:23:27"
 *				"Feb-7-1997 15:23:27"
 *				"2-7-1997 15:23:27"
 *				"1997-2-7 15:23:27"
 *				"1997.038 15:23:27"		(day of year 1-366)
 *		Also supports input in compact time:
 *				"970207 152327"
 *				"97038 152327"
2778 2779
 *
 * Use the system-provided functions to get the current time zone
2780
 *	if not specified in the input string.
2781
 * If the date is outside the time_t system-supported time range,
2782
 *	then assume GMT time zone. - tgl 97/05/27
2783 2784
 */
int
2785
DecodeDateTime(char **field, int *ftype, int nf,
2786
			   int *dtype, struct tm * tm, double *fsec, int *tzp)
2787
{
2788 2789 2790 2791 2792 2793 2794 2795
	int			fmask = 0,
				tmask,
				type;
	int			i;
	int			flen,
				val;
	int			mer = HR24;
	int			bc = FALSE;
2796 2797 2798 2799 2800 2801 2802 2803 2804 2805

	*dtype = DTK_DATE;
	tm->tm_hour = 0;
	tm->tm_min = 0;
	tm->tm_sec = 0;
	*fsec = 0;
	tm->tm_isdst = -1;			/* don't know daylight savings time status
								 * apriori */
	if (tzp != NULL)
		*tzp = 0;
2806

2807 2808 2809 2810 2811 2812 2813
	for (i = 0; i < nf; i++)
	{
#ifdef DATEDEBUG
		printf("DecodeDateTime- field[%d] is %s (type %d)\n", i, field[i], ftype[i]);
#endif
		switch (ftype[i])
		{
2814 2815
			case DTK_DATE:
				if (DecodeDate(field[i], fmask, &tmask, tm) != 0)
2816 2817 2818
					return -1;
				break;

2819 2820
			case DTK_TIME:
				if (DecodeTime(field[i], fmask, &tmask, tm, fsec) != 0)
2821 2822 2823
					return -1;

				/*
2824 2825
				 * check upper limit on hours; other limits checked in
				 * DecodeTime()
2826
				 */
2827
				if (tm->tm_hour > 23)
2828 2829 2830
					return -1;
				break;

2831
			case DTK_TZ:
2832 2833
				if (tzp == NULL)
					return -1;
2834 2835 2836
				if (DecodeTimezone(field[i], tzp) != 0)
					return -1;
				tmask = DTK_M(TZ);
2837 2838
				break;

2839 2840
			case DTK_NUMBER:
				flen = strlen(field[i]);
2841

2842 2843 2844 2845
				if (flen > 4)
				{
					if (DecodeNumberField(flen, field[i], fmask, &tmask, tm, fsec) != 0)
						return -1;
2846

2847 2848 2849 2850 2851 2852
				}
				else
				{
					if (DecodeNumber(flen, field[i], fmask, &tmask, tm, fsec) != 0)
						return -1;
				}
2853 2854
				break;

2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984
			case DTK_STRING:
			case DTK_SPECIAL:
				type = DecodeSpecial(i, field[i], &val);
#ifdef DATEDEBUG
				printf("DecodeDateTime- special field[%d] %s type=%d value=%d\n", i, field[i], type, val);
#endif
				if (type == IGNORE)
					continue;

				tmask = DTK_M(type);
				switch (type)
				{
					case RESERV:
#ifdef DATEDEBUG
						printf("DecodeDateTime- RESERV field %s value is %d\n", field[i], val);
#endif
						switch (val)
						{
							case DTK_NOW:
								tmask = (DTK_DATE_M | DTK_TIME_M | DTK_M(TZ));
								*dtype = DTK_DATE;
								GetCurrentTime(tm);
								if (tzp != NULL)
									*tzp = CTimeZone;
								break;

							case DTK_YESTERDAY:
								tmask = DTK_DATE_M;
								*dtype = DTK_DATE;
								GetCurrentTime(tm);
								j2date((date2j(tm->tm_year, tm->tm_mon, tm->tm_mday) - 1),
								&tm->tm_year, &tm->tm_mon, &tm->tm_mday);
								tm->tm_hour = 0;
								tm->tm_min = 0;
								tm->tm_sec = 0;
								break;

							case DTK_TODAY:
								tmask = DTK_DATE_M;
								*dtype = DTK_DATE;
								GetCurrentTime(tm);
								tm->tm_hour = 0;
								tm->tm_min = 0;
								tm->tm_sec = 0;
								break;

							case DTK_TOMORROW:
								tmask = DTK_DATE_M;
								*dtype = DTK_DATE;
								GetCurrentTime(tm);
								j2date((date2j(tm->tm_year, tm->tm_mon, tm->tm_mday) + 1),
								&tm->tm_year, &tm->tm_mon, &tm->tm_mday);
								tm->tm_hour = 0;
								tm->tm_min = 0;
								tm->tm_sec = 0;
								break;

							case DTK_ZULU:
								tmask = (DTK_TIME_M | DTK_M(TZ));
								*dtype = DTK_DATE;
								tm->tm_hour = 0;
								tm->tm_min = 0;
								tm->tm_sec = 0;
								if (tzp != NULL)
									*tzp = 0;
								break;

							default:
								*dtype = val;
						}

						break;

					case MONTH:
#ifdef DATEDEBUG
						printf("DecodeDateTime- month field %s value is %d\n", field[i], val);
#endif
						tm->tm_mon = val;
						break;

						/*
						 * daylight savings time modifier (solves "MET
						 * DST" syntax)
						 */
					case DTZMOD:
						tmask |= DTK_M(DTZ);
						tm->tm_isdst = 1;
						if (tzp == NULL)
							return -1;
						*tzp += val * 60;
						break;

					case DTZ:

						/*
						 * set mask for TZ here _or_ check for DTZ later
						 * when getting default timezone
						 */
						tmask |= DTK_M(TZ);
						tm->tm_isdst = 1;
						if (tzp == NULL)
							return -1;
						*tzp = val * 60;
						break;

					case TZ:
						tm->tm_isdst = 0;
						if (tzp == NULL)
							return -1;
						*tzp = val * 60;
						break;

					case IGNORE:
						break;

					case AMPM:
						mer = val;
						break;

					case ADBC:
						bc = (val == BC);
						break;

					case DOW:
						tm->tm_wday = val;
						break;

					default:
						return -1;
				}
2985 2986 2987 2988
				break;

			default:
				return -1;
2989
		}
2990 2991

#ifdef DATEDEBUG
2992 2993
		printf("DecodeDateTime- field[%d] %s (%08x/%08x) value is %d\n",
			   i, field[i], fmask, tmask, val);
2994 2995
#endif

2996 2997 2998
		if (tmask & fmask)
			return -1;
		fmask |= tmask;
2999
	}
3000

3001 3002 3003
	/* there is no year zero in AD/BC notation; i.e. "1 BC" == year 0 */
	if (bc)
		tm->tm_year = -(tm->tm_year - 1);
3004

3005 3006
	if ((mer != HR24) && (tm->tm_hour > 12))
		return -1;
3007 3008 3009
	if ((mer == AM) && (tm->tm_hour == 12))
		tm->tm_hour = 0;
	else if ((mer == PM) && (tm->tm_hour != 12))
3010
		tm->tm_hour += 12;
3011 3012

#ifdef DATEDEBUG
3013 3014 3015
	printf("DecodeDateTime- mask %08x (%08x)", fmask, DTK_DATE_M);
	printf(" set y%04d m%02d d%02d", tm->tm_year, tm->tm_mon, tm->tm_mday);
	printf(" %02d:%02d:%02d\n", tm->tm_hour, tm->tm_min, tm->tm_sec);
3016 3017
#endif

3018
	if ((*dtype == DTK_DATE) && ((fmask & DTK_DATE_M) != DTK_DATE_M))
3019
		return ((fmask & DTK_TIME_M) == DTK_TIME_M) ? 1 : -1;
3020

3021 3022 3023 3024
	/* timezone not specified? then find local timezone if possible */
	if ((*dtype == DTK_DATE) && ((fmask & DTK_DATE_M) == DTK_DATE_M)
		&& (tzp != NULL) && (!(fmask & DTK_M(TZ))))
	{
3025

3026 3027 3028 3029 3030 3031
		/*
		 * daylight savings time modifier but no standard timezone? then
		 * error
		 */
		if (fmask & DTK_M(DTZMOD))
			return -1;
3032

3033 3034
		if (IS_VALID_UTIME(tm->tm_year, tm->tm_mon, tm->tm_mday))
		{
3035
#ifdef USE_POSIX_TIME
3036 3037 3038 3039 3040 3041
			tm->tm_year -= 1900;
			tm->tm_mon -= 1;
			tm->tm_isdst = -1;
			mktime(tm);
			tm->tm_year += 1900;
			tm->tm_mon += 1;
3042

3043
#if defined(HAVE_TM_ZONE)
3044
			*tzp = -(tm->tm_gmtoff);	/* tm_gmtoff is Sun/DEC-ism */
3045 3046 3047 3048
#elif defined(HAVE_INT_TIMEZONE)
			*tzp = ((tm->tm_isdst > 0) ? (timezone - 3600) : timezone);
#else
#error USE_POSIX_TIME is defined but neither HAVE_TM_ZONE or HAVE_INT_TIMEZONE are defined
3049
#endif
3050

3051 3052
#else							/* !USE_POSIX_TIME */
			*tzp = CTimeZone;
3053
#endif
3054 3055 3056 3057 3058 3059
		}
		else
		{
			tm->tm_isdst = 0;
			*tzp = 0;
		}
3060
	}
3061

3062
	return 0;
3063
}	/* DecodeDateTime() */
3064 3065 3066 3067 3068 3069


/* DecodeTimeOnly()
 * Interpret parsed string as time fields only.
 */
int
3070
DecodeTimeOnly(char **field, int *ftype, int nf, int *dtype, struct tm * tm, double *fsec)
3071
{
3072 3073 3074 3075 3076 3077 3078
	int			fmask,
				tmask,
				type;
	int			i;
	int			flen,
				val;
	int			mer = HR24;
3079 3080 3081 3082 3083

	*dtype = DTK_TIME;
	tm->tm_hour = 0;
	tm->tm_min = 0;
	tm->tm_sec = 0;
3084 3085
	tm->tm_isdst = -1;			/* don't know daylight savings time status
								 * apriori */
3086
	*fsec = 0;
3087

3088
	fmask = DTK_DATE_M;
3089

3090 3091
	for (i = 0; i < nf; i++)
	{
3092
#ifdef DATEDEBUG
3093
		printf("DecodeTimeOnly- field[%d] is %s (type %d)\n", i, field[i], ftype[i]);
3094
#endif
3095 3096
		switch (ftype[i])
		{
3097 3098 3099 3100
			case DTK_TIME:
				if (DecodeTime(field[i], fmask, &tmask, tm, fsec) != 0)
					return -1;
				break;
3101

3102 3103
			case DTK_NUMBER:
				flen = strlen(field[i]);
3104

3105 3106 3107
				if (DecodeNumberField(flen, field[i], fmask, &tmask, tm, fsec) != 0)
					return -1;
				break;
3108

3109 3110 3111
			case DTK_STRING:
			case DTK_SPECIAL:
				type = DecodeSpecial(i, field[i], &val);
3112
#ifdef DATEDEBUG
3113
				printf("DecodeTimeOnly- special field[%d] %s type=%d value=%d\n", i, field[i], type, val);
3114
#endif
3115 3116
				if (type == IGNORE)
					continue;
3117

3118 3119 3120 3121
				tmask = DTK_M(type);
				switch (type)
				{
					case RESERV:
3122
#ifdef DATEDEBUG
3123
						printf("DecodeTimeOnly- RESERV field %s value is %d\n", field[i], val);
3124
#endif
3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156
						switch (val)
						{
							case DTK_NOW:
								tmask = DTK_TIME_M;
								*dtype = DTK_TIME;
								GetCurrentTime(tm);
								break;

							case DTK_ZULU:
								tmask = (DTK_TIME_M | DTK_M(TZ));
								*dtype = DTK_TIME;
								tm->tm_hour = 0;
								tm->tm_min = 0;
								tm->tm_sec = 0;
								tm->tm_isdst = 0;
								break;

							default:
								return -1;
						}

						break;

					case IGNORE:
						break;

					case AMPM:
						mer = val;
						break;

					default:
						return -1;
3157 3158 3159 3160 3161
				}
				break;

			default:
				return -1;
3162
		}
3163

3164 3165 3166
		if (tmask & fmask)
			return -1;
		fmask |= tmask;
3167 3168

#ifdef DATEDEBUG
3169
		printf("DecodeTimeOnly- field[%d] %s value is %d\n", i, field[i], val);
3170
#endif
3171
	}
3172 3173

#ifdef DATEDEBUG
3174 3175
	printf("DecodeTimeOnly- mask %08x (%08x)", fmask, DTK_TIME_M);
	printf(" %02d:%02d:%02d (%f)\n", tm->tm_hour, tm->tm_min, tm->tm_sec, *fsec);
3176 3177
#endif

3178 3179
	if ((mer != HR24) && (tm->tm_hour > 12))
		return -1;
3180 3181 3182
	if ((mer == AM) && (tm->tm_hour == 12))
		tm->tm_hour = 0;
	else if ((mer == PM) && (tm->tm_hour != 12))
3183
		tm->tm_hour += 12;
3184

3185 3186
	if ((fmask & DTK_TIME_M) != DTK_TIME_M)
		return -1;
3187

3188
	return 0;
3189
}	/* DecodeTimeOnly() */
3190 3191 3192 3193 3194 3195


/* DecodeDate()
 * Decode date string which includes delimiters.
 * Insist on a complete set of fields.
 */
3196
static int
3197
DecodeDate(char *str, int fmask, int *tmask, struct tm * tm)
3198
{
3199
	double		fsec;
3200

3201 3202 3203 3204 3205 3206 3207
	int			nf = 0;
	int			i,
				len;
	int			type,
				val,
				dmask = 0;
	char	   *field[MAXDATEFIELDS];
3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226

	/* parse this string... */
	while ((*str != '\0') && (nf < MAXDATEFIELDS))
	{
		/* skip field separators */
		while (!isalnum(*str))
			str++;

		field[nf] = str;
		if (isdigit(*str))
		{
			while (isdigit(*str))
				str++;
		}
		else if (isalpha(*str))
		{
			while (isalpha(*str))
				str++;
		}
3227

3228 3229 3230
		if (*str != '\0')
			*str++ = '\0';
		nf++;
3231
	}
3232

3233 3234 3235
	/* don't allow too many fields */
	if (nf > 3)
		return -1;
3236

3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250
	*tmask = 0;

	/* look first for text fields, since that will be unambiguous month */
	for (i = 0; i < nf; i++)
	{
		if (isalpha(*field[i]))
		{
			type = DecodeSpecial(i, field[i], &val);
			if (type == IGNORE)
				continue;

			dmask = DTK_M(type);
			switch (type)
			{
3251
				case MONTH:
3252
#ifdef DATEDEBUG
3253
					printf("DecodeDate- month field %s value is %d\n", field[i], val);
3254
#endif
3255 3256
					tm->tm_mon = val;
					break;
3257

3258
				default:
3259
#ifdef DATEDEBUG
3260
					printf("DecodeDate- illegal field %s value is %d\n", field[i], val);
3261
#endif
3262
					return -1;
3263 3264 3265
			}
			if (fmask & dmask)
				return -1;
3266

3267 3268
			fmask |= dmask;
			*tmask |= dmask;
3269

3270 3271 3272
			/* mark this field as being completed */
			field[i] = NULL;
		}
3273
	}
3274

3275 3276 3277 3278 3279
	/* now pick up remaining numeric fields */
	for (i = 0; i < nf; i++)
	{
		if (field[i] == NULL)
			continue;
3280

3281 3282
		if ((len = strlen(field[i])) <= 0)
			return -1;
3283

3284 3285
		if (DecodeNumber(len, field[i], fmask, &dmask, tm, &fsec) != 0)
			return -1;
3286

3287 3288
		if (fmask & dmask)
			return -1;
3289

3290 3291 3292
		fmask |= dmask;
		*tmask |= dmask;
	}
3293

3294
	return 0;
3295
}	/* DecodeDate() */
3296 3297 3298 3299


/* DecodeTime()
 * Decode time string which includes delimiters.
3300
 * Only check the lower limit on hours, since this same code
3301
 *	can be used to represent time spans.
3302
 */
3303
static int
3304
DecodeTime(char *str, int fmask, int *tmask, struct tm * tm, double *fsec)
3305
{
3306
	char	   *cp;
3307

3308
	*tmask = DTK_TIME_M;
3309

3310 3311 3312 3313 3314 3315 3316 3317 3318
	tm->tm_hour = strtol(str, &cp, 10);
	if (*cp != ':')
		return -1;
	str = cp + 1;
	tm->tm_min = strtol(str, &cp, 10);
	if (*cp == '\0')
	{
		tm->tm_sec = 0;
		*fsec = 0;
3319

3320 3321 3322 3323
	}
	else if (*cp != ':')
	{
		return -1;
3324

3325
	}
3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341
	else
	{
		str = cp + 1;
		tm->tm_sec = strtol(str, &cp, 10);
		if (*cp == '\0')
			*fsec = 0;
		else if (*cp == '.')
		{
			str = cp;
			*fsec = strtod(str, &cp);
			if (cp == str)
				return -1;
		}
		else
			return -1;
	}
3342

3343 3344 3345 3346 3347
	/* do a sanity check */
	if ((tm->tm_hour < 0)
		|| (tm->tm_min < 0) || (tm->tm_min > 59)
		|| (tm->tm_sec < 0) || (tm->tm_sec > 59))
		return -1;
3348

3349
	return 0;
3350
}	/* DecodeTime() */
3351 3352 3353 3354 3355


/* DecodeNumber()
 * Interpret numeric field as a date value in context.
 */
3356
static int
3357
DecodeNumber(int flen, char *str, int fmask, int *tmask, struct tm * tm, double *fsec)
3358
{
3359 3360
	int			val;
	char	   *cp;
3361

3362
	*tmask = 0;
3363

3364 3365 3366 3367 3368 3369 3370 3371 3372
	val = strtol(str, &cp, 10);
	if (cp == str)
		return -1;
	if (*cp == '.')
	{
		*fsec = strtod(cp, &cp);
		if (*cp != '\0')
			return -1;
	}
3373 3374

#ifdef DATEDEBUG
3375
	printf("DecodeNumber- %s is %d fmask=%08x tmask=%08x\n", str, val, fmask, *tmask);
3376 3377
#endif

3378 3379 3380
	/* enough digits to be unequivocal year? */
	if (flen == 4)
	{
3381
#ifdef DATEDEBUG
3382
		printf("DecodeNumber- match %d (%s) as year\n", val, str);
3383
#endif
3384 3385 3386 3387 3388 3389 3390 3391
		*tmask = DTK_M(YEAR);

		/* already have a year? then see if we can substitute... */
		if (fmask & DTK_M(YEAR))
		{
			if ((!(fmask & DTK_M(DAY)))
				&& ((tm->tm_year >= 1) && (tm->tm_year <= 31)))
			{
3392
#ifdef DATEDEBUG
3393
				printf("DecodeNumber- misidentified year previously; swap with day %d\n", tm->tm_mday);
3394
#endif
3395 3396 3397 3398
				tm->tm_mday = tm->tm_year;
				*tmask = DTK_M(DAY);
			}
		}
3399

3400
		tm->tm_year = val;
3401

3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416
		/* special case day of year? */
	}
	else if ((flen == 3) && (fmask & DTK_M(YEAR))
			 && ((val >= 1) && (val <= 366)))
	{
		*tmask = (DTK_M(DOY) | DTK_M(MONTH) | DTK_M(DAY));
		tm->tm_yday = val;
		j2date((date2j(tm->tm_year, 1, 1) + tm->tm_yday - 1),
			   &tm->tm_year, &tm->tm_mon, &tm->tm_mday);

		/* already have year? then could be month */
	}
	else if ((fmask & DTK_M(YEAR)) && (!(fmask & DTK_M(MONTH)))
			 && ((val >= 1) && (val <= 12)))
	{
3417
#ifdef DATEDEBUG
3418
		printf("DecodeNumber- match %d (%s) as month\n", val, str);
3419
#endif
3420 3421
		*tmask = DTK_M(MONTH);
		tm->tm_mon = val;
3422

3423 3424 3425 3426 3427 3428
		/* no year and EuroDates enabled? then could be day */
	}
	else if ((EuroDates || (fmask & DTK_M(MONTH)))
			 && (!(fmask & DTK_M(YEAR)) && !(fmask & DTK_M(DAY)))
			 && ((val >= 1) && (val <= 31)))
	{
3429
#ifdef DATEDEBUG
3430
		printf("DecodeNumber- match %d (%s) as day\n", val, str);
3431
#endif
3432 3433
		*tmask = DTK_M(DAY);
		tm->tm_mday = val;
3434

3435 3436 3437 3438
	}
	else if ((!(fmask & DTK_M(MONTH)))
			 && ((val >= 1) && (val <= 12)))
	{
3439
#ifdef DATEDEBUG
3440
		printf("DecodeNumber- (2) match %d (%s) as month\n", val, str);
3441
#endif
3442 3443
		*tmask = DTK_M(MONTH);
		tm->tm_mon = val;
3444

3445 3446 3447 3448
	}
	else if ((!(fmask & DTK_M(DAY)))
			 && ((val >= 1) && (val <= 31)))
	{
3449
#ifdef DATEDEBUG
3450
		printf("DecodeNumber- (2) match %d (%s) as day\n", val, str);
3451
#endif
3452 3453
		*tmask = DTK_M(DAY);
		tm->tm_mday = val;
3454

3455 3456 3457
	}
	else if (!(fmask & DTK_M(YEAR)))
	{
3458
#ifdef DATEDEBUG
3459
		printf("DecodeNumber- (2) match %d (%s) as year\n", val, str);
3460
#endif
3461 3462 3463 3464 3465 3466
		*tmask = DTK_M(YEAR);
		tm->tm_year = val;
		if (tm->tm_year < 70)
			tm->tm_year += 2000;
		else if (tm->tm_year < 100)
			tm->tm_year += 1900;
3467

3468 3469 3470
	}
	else
		return -1;
3471

3472
	return 0;
3473
}	/* DecodeNumber() */
3474 3475 3476 3477 3478


/* DecodeNumberField()
 * Interpret numeric string as a concatenated date field.
 */
3479
static int
3480
DecodeNumberField(int len, char *str, int fmask, int *tmask, struct tm * tm, double *fsec)
3481
{
3482
	char	   *cp;
3483

3484 3485 3486
	/* yyyymmdd? */
	if (len == 8)
	{
3487
#ifdef DATEDEBUG
3488
		printf("DecodeNumberField- %s is 8 character date fmask=%08x tmask=%08x\n", str, fmask, *tmask);
3489 3490
#endif

3491
		*tmask = DTK_DATE_M;
3492

3493 3494 3495 3496 3497
		tm->tm_mday = atoi(str + 6);
		*(str + 6) = '\0';
		tm->tm_mon = atoi(str + 4);
		*(str + 4) = '\0';
		tm->tm_year = atoi(str + 0);
3498

3499 3500 3501 3502
		/* yymmdd or hhmmss? */
	}
	else if (len == 6)
	{
3503
#ifdef DATEDEBUG
3504
		printf("DecodeNumberField- %s is 6 characters fmask=%08x tmask=%08x\n", str, fmask, *tmask);
3505
#endif
3506 3507
		if (fmask & DTK_DATE_M)
		{
3508
#ifdef DATEDEBUG
3509
			printf("DecodeNumberField- %s is time field fmask=%08x tmask=%08x\n", str, fmask, *tmask);
3510
#endif
3511 3512 3513 3514 3515 3516
			*tmask = DTK_TIME_M;
			tm->tm_sec = atoi(str + 4);
			*(str + 4) = '\0';
			tm->tm_min = atoi(str + 2);
			*(str + 2) = '\0';
			tm->tm_hour = atoi(str + 0);
3517

3518 3519 3520
		}
		else
		{
3521
#ifdef DATEDEBUG
3522
			printf("DecodeNumberField- %s is date field fmask=%08x tmask=%08x\n", str, fmask, *tmask);
3523
#endif
3524 3525 3526 3527 3528 3529 3530
			*tmask = DTK_DATE_M;
			tm->tm_mday = atoi(str + 4);
			*(str + 4) = '\0';
			tm->tm_mon = atoi(str + 2);
			*(str + 2) = '\0';
			tm->tm_year = atoi(str + 0);
		}
3531

3532 3533 3534
	}
	else if (strchr(str, '.') != NULL)
	{
3535
#ifdef DATEDEBUG
3536
		printf("DecodeNumberField- %s is time field fmask=%08x tmask=%08x\n", str, fmask, *tmask);
3537
#endif
3538 3539 3540 3541 3542 3543 3544 3545 3546 3547
		*tmask = DTK_TIME_M;
		tm->tm_sec = strtod((str + 4), &cp);
		if (cp == (str + 4))
			return -1;
		if (*cp == '.')
			*fsec = strtod(cp, NULL);
		*(str + 4) = '\0';
		tm->tm_min = strtod((str + 2), &cp);
		*(str + 2) = '\0';
		tm->tm_hour = strtod((str + 0), &cp);
3548

3549 3550 3551
	}
	else
		return -1;
3552

3553
	return 0;
3554
}	/* DecodeNumberField() */
3555 3556 3557 3558 3559


/* DecodeTimezone()
 * Interpret string as a numeric timezone.
 */
3560
static int
3561
DecodeTimezone(char *str, int *tzp)
3562
{
3563 3564 3565 3566 3567
	int			tz;
	int			hr,
				min;
	char	   *cp;
	int			len;
3568

3569 3570
	/* assume leading character is "+" or "-" */
	hr = strtol((str + 1), &cp, 10);
3571

3572 3573 3574 3575
	/* explicit delimiter? */
	if (*cp == ':')
	{
		min = strtol((cp + 1), &cp, 10);
3576

3577 3578 3579 3580 3581 3582 3583
		/* otherwise, might have run things together... */
	}
	else if ((*cp == '\0') && ((len = strlen(str)) > 3))
	{
		min = strtol((str + len - 2), &cp, 10);
		*(str + len - 2) = '\0';
		hr = strtol((str + 1), &cp, 10);
3584

3585 3586 3587
	}
	else
		min = 0;
3588

3589 3590 3591
	tz = (hr * 60 + min) * 60;
	if (*str == '-')
		tz = -tz;
3592

3593
	*tzp = -tz;
3594
	return *cp != '\0';
3595
}	/* DecodeTimezone() */
3596 3597 3598 3599 3600


/* DecodeSpecial()
 * Decode text string using lookup table.
 * Implement a cache lookup since it is likely that dates
3601
 *	will be related in format.
3602
 */
3603
static int
3604 3605
DecodeSpecial(int field, char *lowtoken, int *val)
{
3606 3607
	int			type;
	datetkn    *tp;
3608 3609

#if USE_DATE_CACHE
3610 3611 3612 3613 3614
	if ((datecache[field] != NULL)
		&& (strncmp(lowtoken, datecache[field]->token, TOKMAXLEN) == 0))
		tp = datecache[field];
	else
	{
3615
#endif
3616
		tp = datebsearch(lowtoken, datetktbl, szdatetktbl);
3617
#if USE_DATE_CACHE
3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630
	}
	datecache[field] = tp;
#endif
	if (tp == NULL)
	{
		type = IGNORE;
		*val = 0;
	}
	else
	{
		type = tp->type;
		switch (type)
		{
3631 3632 3633 3634 3635
			case TZ:
			case DTZ:
			case DTZMOD:
				*val = FROMVAL(tp);
				break;
3636

3637 3638 3639
			default:
				*val = tp->value;
				break;
3640
		}
3641
	}
3642

3643
	return type;
3644
}	/* DecodeSpecial() */
3645 3646 3647 3648 3649 3650


/* DecodeDateDelta()
 * Interpret previously parsed fields for general time interval.
 * Return 0 if decoded and -1 if problems.
 *
3651
 * Allow "date" field DTK_DATE since this could be just
3652
 *	an unsigned floating point number. - thomas 1997-11-16
3653
 *
3654
 * Allow ISO-style time span, with implicit units on number of days
3655
 *	preceeding an hh:mm:ss field. - thomas 1998-04-30
3656 3657
 */
int
3658
DecodeDateDelta(char **field, int *ftype, int nf, int *dtype, struct tm * tm, double *fsec)
3659
{
3660
	int			is_before = FALSE;
3661

3662
	char	   *cp;
3663 3664 3665
	int			fmask = 0,
				tmask,
				type;
3666
	int			i;
3667 3668
	int			flen,
				val;
3669
	double		fval;
3670
	double		sec;
3671

3672
	*dtype = DTK_DELTA;
3673

3674
	type = DTK_SECOND;
3675 3676 3677 3678 3679 3680 3681
	tm->tm_year = 0;
	tm->tm_mon = 0;
	tm->tm_mday = 0;
	tm->tm_hour = 0;
	tm->tm_min = 0;
	tm->tm_sec = 0;
	*fsec = 0;
3682

3683 3684
	/* read through list backwards to pick up units before values */
	for (i = nf - 1; i >= 0; i--)
3685
	{
3686
#ifdef DATEDEBUG
3687
		printf("DecodeDateDelta- field[%d] is %s (type %d)\n", i, field[i], ftype[i]);
3688
#endif
3689 3690
		switch (ftype[i])
		{
3691 3692 3693
			case DTK_TIME:
				if (DecodeTime(field[i], fmask, &tmask, tm, fsec) != 0)
					return -1;
3694
				type = DTK_DAY;
3695
				break;
3696

3697
			case DTK_TZ:
3698 3699 3700 3701

				/*
				 * Timezone is a token with a leading sign character and
				 * otherwise the same as a non-signed numeric field
3702
				 */
3703
			case DTK_DATE:
3704 3705 3706 3707
			case DTK_NUMBER:
				val = strtol(field[i], &cp, 10);
				if (*cp == '.')
				{
3708 3709 3710 3711 3712 3713
					fval = strtod(cp, &cp);
					if (*cp != '\0')
						return -1;

					if (val < 0)
						fval = -(fval);
3714
				}
3715 3716 3717 3718 3719
				else if (*cp == '\0')
					fval = 0;
				else
					return -1;

3720 3721
				flen = strlen(field[i]);
				tmask = 0;		/* DTK_M(type); */
3722

3723 3724 3725
				switch (type)
				{
					case DTK_MICROSEC:
3726
						*fsec += ((val + fval) * 1e-6);
3727 3728 3729
						break;

					case DTK_MILLISEC:
3730
						*fsec += ((val + fval) * 1e-3);
3731 3732 3733 3734
						break;

					case DTK_SECOND:
						tm->tm_sec += val;
3735
						*fsec += fval;
3736 3737 3738 3739 3740
						tmask = DTK_M(SECOND);
						break;

					case DTK_MINUTE:
						tm->tm_min += val;
3741 3742
						if (fval != 0)
							tm->tm_sec += (fval * 60);
3743 3744 3745 3746 3747
						tmask = DTK_M(MINUTE);
						break;

					case DTK_HOUR:
						tm->tm_hour += val;
3748 3749
						if (fval != 0)
							tm->tm_sec += (fval * 3600);
3750 3751 3752 3753 3754
						tmask = DTK_M(HOUR);
						break;

					case DTK_DAY:
						tm->tm_mday += val;
3755 3756
						if (fval != 0)
							tm->tm_sec += (fval * 86400);
3757 3758 3759 3760 3761
						tmask = ((fmask & DTK_M(DAY)) ? 0 : DTK_M(DAY));
						break;

					case DTK_WEEK:
						tm->tm_mday += val * 7;
3762
						if (fval != 0)
3763
							tm->tm_sec += (fval * (7 * 86400));
3764 3765 3766 3767 3768
						tmask = ((fmask & DTK_M(DAY)) ? 0 : DTK_M(DAY));
						break;

					case DTK_MONTH:
						tm->tm_mon += val;
3769
						if (fval != 0)
3770
							tm->tm_sec += (fval * (30 * 86400));
3771 3772 3773 3774 3775
						tmask = DTK_M(MONTH);
						break;

					case DTK_YEAR:
						tm->tm_year += val;
3776 3777
						if (fval != 0)
							tm->tm_mon += (fval * 12);
3778 3779 3780 3781 3782
						tmask = ((fmask & DTK_M(YEAR)) ? 0 : DTK_M(YEAR));
						break;

					case DTK_DECADE:
						tm->tm_year += val * 10;
3783 3784
						if (fval != 0)
							tm->tm_mon += (fval * 120);
3785 3786 3787 3788 3789
						tmask = ((fmask & DTK_M(YEAR)) ? 0 : DTK_M(YEAR));
						break;

					case DTK_CENTURY:
						tm->tm_year += val * 100;
3790 3791
						if (fval != 0)
							tm->tm_mon += (fval * 1200);
3792 3793 3794 3795 3796
						tmask = ((fmask & DTK_M(YEAR)) ? 0 : DTK_M(YEAR));
						break;

					case DTK_MILLENIUM:
						tm->tm_year += val * 1000;
3797 3798
						if (fval != 0)
							tm->tm_mon += (fval * 12000);
3799 3800 3801 3802 3803 3804
						tmask = ((fmask & DTK_M(YEAR)) ? 0 : DTK_M(YEAR));
						break;

					default:
						return -1;
				}
3805 3806
				break;

3807 3808 3809
			case DTK_STRING:
			case DTK_SPECIAL:
				type = DecodeUnits(i, field[i], &val);
3810
#ifdef DATEDEBUG
3811
				printf("DecodeDateDelta- special field[%d] %s type=%d value=%d\n", i, field[i], type, val);
3812
#endif
3813 3814
				if (type == IGNORE)
					continue;
3815

3816 3817 3818 3819
				tmask = 0;		/* DTK_M(type); */
				switch (type)
				{
					case UNITS:
3820
#ifdef DATEDEBUG
3821
						printf("DecodeDateDelta- UNITS field %s value is %d\n", field[i], val);
3822
#endif
3823 3824
						type = val;
						break;
3825

3826 3827 3828 3829 3830 3831 3832 3833 3834
					case AGO:
						is_before = TRUE;
						type = val;
						break;

					case RESERV:
						tmask = (DTK_DATE_M || DTK_TIME_M);
						*dtype = val;
						break;
3835

3836 3837 3838
					default:
						return -1;
				}
3839
				break;
3840

3841 3842 3843
			default:
				return -1;
		}
3844 3845

#ifdef DATEDEBUG
3846 3847
		printf("DecodeDateDelta- (%08x/%08x) field[%d] %s value is %d\n",
			   fmask, tmask, i, field[i], val);
3848 3849
#endif

3850 3851 3852 3853
		if (tmask & fmask)
			return -1;
		fmask |= tmask;
	}
3854

3855 3856
	if (*fsec != 0)
	{
3857
		TMODULO(*fsec, sec, 1e0);
3858 3859
		tm->tm_sec += sec;
	}
3860

3861 3862 3863 3864 3865 3866 3867 3868 3869 3870
	if (is_before)
	{
		*fsec = -(*fsec);
		tm->tm_sec = -(tm->tm_sec);
		tm->tm_min = -(tm->tm_min);
		tm->tm_hour = -(tm->tm_hour);
		tm->tm_mday = -(tm->tm_mday);
		tm->tm_mon = -(tm->tm_mon);
		tm->tm_year = -(tm->tm_year);
	}
3871 3872

#ifdef DATEDEBUG
3873 3874 3875
	printf("DecodeDateDelta- mask %08x (%08x)", fmask, DTK_DATE_M);
	printf(" set y%04d m%02d d%02d", tm->tm_year, tm->tm_mon, tm->tm_mday);
	printf(" %02d:%02d:%02d\n", tm->tm_hour, tm->tm_min, tm->tm_sec);
3876 3877
#endif

3878
	/* ensure that at least one time field has been found */
3879
	return (fmask != 0) ? 0 : -1;
3880
}	/* DecodeDateDelta() */
3881 3882 3883 3884 3885 3886


/* DecodeUnits()
 * Decode text string using lookup table.
 * This routine supports time interval decoding.
 */
3887
static int
3888 3889
DecodeUnits(int field, char *lowtoken, int *val)
{
3890 3891
	int			type;
	datetkn    *tp;
3892 3893

#if USE_DATE_CACHE
3894 3895 3896 3897 3898
	if ((deltacache[field] != NULL)
		&& (strncmp(lowtoken, deltacache[field]->token, TOKMAXLEN) == 0))
		tp = deltacache[field];
	else
	{
3899
#endif
3900
		tp = datebsearch(lowtoken, deltatktbl, szdeltatktbl);
3901
#if USE_DATE_CACHE
3902 3903
	}
	deltacache[field] = tp;
3904
#endif
3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916
	if (tp == NULL)
	{
		type = IGNORE;
		*val = 0;
	}
	else
	{
		type = tp->type;
		if ((type == TZ) || (type == DTZ))
			*val = FROMVAL(tp);
		else
			*val = tp->value;
3917
	}
3918

3919
	return type;
3920
}	/* DecodeUnits() */
3921 3922


3923
/* datebsearch()
3924 3925 3926
 * Binary search -- from Knuth (6.2.1) Algorithm B.  Special case like this
 * is WAY faster than the generic bsearch().
 */
3927
static datetkn *
3928
datebsearch(char *key, datetkn *base, unsigned int nel)
3929
{
3930
	datetkn    *last = base + nel - 1,
3931
			   *position;
3932
	int			result;
3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947

	while (last >= base)
	{
		position = base + ((last - base) >> 1);
		result = key[0] - position->token[0];
		if (result == 0)
		{
			result = strncmp(key, position->token, TOKMAXLEN);
			if (result == 0)
				return position;
		}
		if (result < 0)
			last = position - 1;
		else
			base = position + 1;
3948
	}
3949
	return NULL;
3950 3951 3952
}


3953 3954 3955
/* EncodeSpecialDateTime()
 * Convert reserved datetime data type to string.
 */
3956 3957
static int
EncodeSpecialDateTime(DateTime dt, char *str)
3958
{
3959 3960 3961 3962 3963
	if (DATETIME_IS_RESERVED(dt))
	{
		if (DATETIME_IS_INVALID(dt))
		{
			strcpy(str, INVALID);
3964

3965 3966 3967 3968
		}
		else if (DATETIME_IS_NOBEGIN(dt))
		{
			strcpy(str, EARLY);
3969

3970 3971 3972 3973
		}
		else if (DATETIME_IS_NOEND(dt))
		{
			strcpy(str, LATE);
3974

3975 3976 3977 3978
		}
		else if (DATETIME_IS_CURRENT(dt))
		{
			strcpy(str, DCURRENT);
3979

3980 3981 3982 3983
		}
		else if (DATETIME_IS_EPOCH(dt))
		{
			strcpy(str, EPOCH);
3984

3985 3986 3987
		}
		else
		{
3988
#ifdef DATEDEBUG
3989
			printf("EncodeSpecialDateTime- unrecognized date\n");
3990
#endif
3991 3992
			strcpy(str, INVALID);
		}
3993
		return TRUE;
3994
	}
3995

3996
	return FALSE;
3997
}	/* EncodeSpecialDateTime() */
3998 3999


4000 4001 4002
/* EncodeDateOnly()
 * Encode date as local time.
 */
4003 4004
int
EncodeDateOnly(struct tm * tm, int style, char *str)
4005
{
4006 4007
	if ((tm->tm_mon < 1) || (tm->tm_mon > 12))
		return -1;
4008

4009
	switch (style)
4010
	{
4011
			/* compatible with ISO date formats */
4012 4013 4014
		case USE_ISO_DATES:
			if (tm->tm_year > 0)
				sprintf(str, "%04d-%02d-%02d",
4015
						tm->tm_year, tm->tm_mon, tm->tm_mday);
4016 4017
			else
				sprintf(str, "%04d-%02d-%02d %s",
4018
					  -(tm->tm_year - 1), tm->tm_mon, tm->tm_mday, "BC");
4019
			break;
4020

4021
			/* compatible with Oracle/Ingres date formats */
4022 4023 4024 4025 4026 4027 4028 4029 4030 4031
		case USE_SQL_DATES:
			if (EuroDates)
				sprintf(str, "%02d/%02d", tm->tm_mday, tm->tm_mon);
			else
				sprintf(str, "%02d/%02d", tm->tm_mon, tm->tm_mday);
			if (tm->tm_year > 0)
				sprintf((str + 5), "/%04d", tm->tm_year);
			else
				sprintf((str + 5), "/%04d %s", -(tm->tm_year - 1), "BC");
			break;
4032

4033
			/* German-style date format */
4034 4035 4036
		case USE_GERMAN_DATES:
			sprintf(str, "%02d.%02d", tm->tm_mday, tm->tm_mon);
			if (tm->tm_year > 0)
4037
				sprintf((str + 5), ".%04d", tm->tm_year);
4038
			else
4039
				sprintf((str + 5), ".%04d %s", -(tm->tm_year - 1), "BC");
4040
			break;
4041

4042
			/* traditional date-only style for Postgres */
4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053
		case USE_POSTGRES_DATES:
		default:
			if (EuroDates)
				sprintf(str, "%02d-%02d", tm->tm_mday, tm->tm_mon);
			else
				sprintf(str, "%02d-%02d", tm->tm_mon, tm->tm_mday);
			if (tm->tm_year > 0)
				sprintf((str + 5), "-%04d", tm->tm_year);
			else
				sprintf((str + 5), "-%04d %s", -(tm->tm_year - 1), "BC");
			break;
4054
	}
4055 4056

#ifdef DATEDEBUG
4057
	printf("EncodeDateOnly- date result is %s\n", str);
4058 4059
#endif

4060
	return TRUE;
4061
}	/* EncodeDateOnly() */
4062 4063 4064 4065 4066


/* EncodeTimeOnly()
 * Encode time fields only.
 */
4067 4068
int
EncodeTimeOnly(struct tm * tm, double fsec, int style, char *str)
4069
{
4070
	double		sec;
4071

4072 4073
	if ((tm->tm_hour < 0) || (tm->tm_hour > 24))
		return -1;
4074

4075
	sec = (tm->tm_sec + fsec);
4076

4077 4078
	sprintf(str, "%02d:%02d:", tm->tm_hour, tm->tm_min);
	sprintf((str + 6), ((fsec != 0) ? "%05.2f" : "%02.0f"), sec);
4079 4080

#ifdef DATEDEBUG
4081
	printf("EncodeTimeOnly- time result is %s\n", str);
4082 4083
#endif

4084
	return TRUE;
4085
}	/* EncodeTimeOnly() */
4086 4087


4088 4089
/* EncodeDateTime()
 * Encode date and time interpreted as local time.
4090
 * Support several date styles:
4091 4092 4093 4094
 *	Postgres - day mon hh:mm:ss yyyy tz
 *	SQL - mm/dd/yyyy hh:mm:ss.ss tz
 *	ISO - yyyy-mm-dd hh:mm:ss+/-tz
 *	German - dd.mm/yyyy hh:mm:ss tz
4095
 * Variants (affects order of month and day for Postgres and SQL styles):
4096 4097
 *	US - mm/dd/yyyy
 *	European - dd/mm/yyyy
4098
 */
4099 4100
int
EncodeDateTime(struct tm * tm, double fsec, int *tzp, char **tzn, int style, char *str)
4101
{
4102 4103 4104 4105
	int			day,
				hour,
				min;
	double		sec;
4106

4107 4108
	if ((tm->tm_mon < 1) || (tm->tm_mon > 12))
		return -1;
4109

4110
	sec = (tm->tm_sec + fsec);
4111 4112

#ifdef DATEDEBUG
4113
#ifdef USE_POSIX_TIME
4114 4115 4116 4117
#if defined(HAVE_TM_ZONE)
	printf("EncodeDateTime- timezone is %s (%s); offset is %ld (%d); daylight is %d (%d)\n",
		   *tzn, tm->tm_zone, (-tm->tm_gmtoff), CTimeZone, tm->tm_isdst, CDayLight);
#elif defined(HAVE_INT_TIMEZONE)
4118 4119
	printf("EncodeDateTime- timezone is %s (%s); offset is %d (%d); daylight is %d (%d)\n",
		   *tzn, tzname[0], *tzp, CTimeZone, tm->tm_isdst, CDayLight);
4120
#else
4121
#error USE_POSIX_TIME is defined but neither HAVE_TM_ZONE or HAVE_INT_TIMEZONE are defined
4122 4123
#endif
#else
4124 4125
	printf("EncodeDateTime- timezone is %s (%s); offset is %d; daylight is %d\n",
		   *tzn, CTZName, CTimeZone, CDayLight);
4126
#endif
4127 4128
#endif

4129
	switch (style)
4130
	{
4131
			/* compatible with ISO date formats */
4132

4133 4134
		case USE_ISO_DATES:
			if (tm->tm_year > 0)
4135
			{
4136
				sprintf(str, "%04d-%02d-%02d %02d:%02d:",
4137
						tm->tm_year, tm->tm_mon, tm->tm_mday, tm->tm_hour, tm->tm_min);
4138 4139 4140
				sprintf((str + 17), ((fsec != 0) ? "%05.2f" : "%02.0f"), sec);

				if ((*tzn != NULL) && (tm->tm_isdst >= 0))
4141
				{
4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152
					if (tzp != NULL)
					{
						hour = -(*tzp / 3600);
						min = ((abs(*tzp) / 60) % 60);
					}
					else
					{
						hour = 0;
						min = 0;
					}
					sprintf((str + strlen(str)), ((min != 0) ? "%+03d:%02d" : "%+03d"), hour, min);
4153
				}
4154

4155 4156 4157
			}
			else
			{
4158 4159
				if (tm->tm_hour || tm->tm_min)
					sprintf(str, "%04d-%02d-%02d %02d:%02d %s",
4160
							-(tm->tm_year - 1), tm->tm_mon, tm->tm_mday, tm->tm_hour, tm->tm_min, "BC");
4161 4162
				else
					sprintf(str, "%04d-%02d-%02d %s",
4163
					  -(tm->tm_year - 1), tm->tm_mon, tm->tm_mday, "BC");
4164
			}
4165
			break;
4166

4167
			/* compatible with Oracle/Ingres date formats */
4168 4169 4170 4171 4172
		case USE_SQL_DATES:
			if (EuroDates)
				sprintf(str, "%02d/%02d", tm->tm_mday, tm->tm_mon);
			else
				sprintf(str, "%02d/%02d", tm->tm_mon, tm->tm_mday);
4173

4174
			if (tm->tm_year > 0)
4175
			{
4176
				sprintf((str + 5), "/%04d %02d:%02d:%05.2f",
4177
						tm->tm_year, tm->tm_hour, tm->tm_min, sec);
4178 4179 4180 4181 4182 4183 4184

				if ((*tzn != NULL) && (tm->tm_isdst >= 0))
				{
					strcpy((str + 22), " ");
					strcpy((str + 23), *tzn);
				}

4185
			}
4186 4187
			else
				sprintf((str + 5), "/%04d %02d:%02d %s",
4188
					  -(tm->tm_year - 1), tm->tm_hour, tm->tm_min, "BC");
4189
			break;
4190

4191
			/* German variant on European style */
4192 4193 4194 4195
		case USE_GERMAN_DATES:
			sprintf(str, "%02d.%02d", tm->tm_mday, tm->tm_mon);
			if (tm->tm_year > 0)
			{
4196
				sprintf((str + 5), ".%04d %02d:%02d:%05.2f",
4197
						tm->tm_year, tm->tm_hour, tm->tm_min, sec);
4198 4199 4200 4201 4202 4203 4204 4205 4206

				if ((*tzn != NULL) && (tm->tm_isdst >= 0))
				{
					strcpy((str + 22), " ");
					strcpy((str + 23), *tzn);
				}

			}
			else
4207
				sprintf((str + 5), ".%04d %02d:%02d %s",
4208
					  -(tm->tm_year - 1), tm->tm_hour, tm->tm_min, "BC");
4209
			break;
4210

4211
			/* backward-compatible with traditional Postgres abstime dates */
4212 4213 4214
		case USE_POSTGRES_DATES:
		default:
			day = date2j(tm->tm_year, tm->tm_mon, tm->tm_mday);
4215
#ifdef DATEDEBUG
4216
			printf("EncodeDateTime- day is %d\n", day);
4217
#endif
4218
			tm->tm_wday = j2day(day);
4219

4220 4221
			strncpy(str, days[tm->tm_wday], 3);
			strcpy((str + 3), " ");
4222

4223 4224 4225 4226 4227 4228
			if (EuroDates)
				sprintf((str + 4), "%02d %3s", tm->tm_mday, months[tm->tm_mon - 1]);
			else
				sprintf((str + 4), "%3s %02d", months[tm->tm_mon - 1], tm->tm_mday);

			if (tm->tm_year > 0)
4229
			{
4230 4231
				sprintf((str + 10), " %02d:%02d", tm->tm_hour, tm->tm_min);
				if (fsec != 0)
4232
				{
4233 4234 4235 4236 4237 4238
					sprintf((str + 16), ":%05.2f %04d", sec, tm->tm_year);
					if ((*tzn != NULL) && (tm->tm_isdst >= 0))
					{
						strcpy((str + 27), " ");
						strcpy((str + 28), *tzn);
					}
4239
				}
4240
				else
4241
				{
4242 4243 4244 4245 4246 4247
					sprintf((str + 16), ":%02.0f %04d", sec, tm->tm_year);
					if ((*tzn != NULL) && (tm->tm_isdst >= 0))
					{
						strcpy((str + 24), " ");
						strcpy((str + 25), *tzn);
					}
4248
				}
4249

4250 4251 4252 4253
			}
			else
			{
				sprintf((str + 10), " %02d:%02d %04d %s",
4254
					  tm->tm_hour, tm->tm_min, -(tm->tm_year - 1), "BC");
4255 4256
			}
			break;
4257
	}
4258

4259
#ifdef DATEDEBUG
4260
	printf("EncodeDateTime- date result is %s\n", str);
4261 4262
#endif

4263
	return TRUE;
4264
}	/* EncodeDateTime() */
4265 4266


4267 4268 4269
/* EncodeTimeSpan()
 * Interpret time structure as a delta time and convert to string.
 *
4270 4271
 * Support "traditional Postgres" and ISO-8601 styles.
 * Actually, afaik ISO does not address time interval formatting,
4272
 *	but this looks similar to the spec for absolute date/time.
4273
 * - thomas 1998-04-30
4274
 */
4275 4276 4277
int
EncodeTimeSpan(struct tm * tm, double fsec, int style, char *str)
{
4278 4279
	int			is_before = FALSE;
	int			is_nonzero = FALSE;
4280
	char	   *cp = str;
4281

4282 4283
	switch (style)
	{
4284
			/* compatible with ISO date formats */
4285
		case USE_ISO_DATES:
4286
			break;
4287 4288

		default:
4289
			strcpy(cp, "@ ");
4290 4291 4292
			cp += strlen(cp);
			break;
	}
4293 4294 4295 4296

	if (tm->tm_year != 0)
	{
		is_before |= (tm->tm_year < 0);
4297
		sprintf(cp, "%d year%s",
4298
				abs(tm->tm_year), ((abs(tm->tm_year) != 1) ? "s" : ""));
4299
		cp += strlen(cp);
4300
		is_nonzero = TRUE;
4301 4302 4303 4304 4305
	}

	if (tm->tm_mon != 0)
	{
		is_before |= (tm->tm_mon < 0);
4306 4307
		sprintf(cp, "%s%d mon%s", (is_nonzero ? " " : ""),
				abs(tm->tm_mon), ((abs(tm->tm_mon) != 1) ? "s" : ""));
4308 4309 4310 4311
		cp += strlen(cp);
		is_nonzero = TRUE;
	}

4312
	switch (style)
4313
	{
4314
			/* compatible with ISO date formats */
4315
		case USE_ISO_DATES:
4316 4317 4318
			if (tm->tm_mday != 0)
			{
				is_before |= (tm->tm_mday < 0);
4319
				sprintf(cp, "%s%d", (is_nonzero ? " " : ""), abs(tm->tm_mday));
4320
				cp += strlen(cp);
4321
				is_nonzero = TRUE;
4322
			}
4323
			is_before |= ((tm->tm_hour < 0) || (tm->tm_min < 0));
4324 4325
			sprintf(cp, "%s%02d:%02d", (is_nonzero ? " " : ""),
					abs(tm->tm_hour), abs(tm->tm_min));
4326
			cp += strlen(cp);
4327 4328
			if ((tm->tm_hour != 0) || (tm->tm_min != 0))
				is_nonzero = TRUE;
4329 4330 4331 4332 4333 4334 4335 4336

			/* fractional seconds? */
			if (fsec != 0)
			{
				fsec += tm->tm_sec;
				is_before |= (fsec < 0);
				sprintf(cp, ":%05.2f", fabs(fsec));
				cp += strlen(cp);
4337
				is_nonzero = TRUE;
4338

4339 4340 4341 4342 4343 4344 4345
				/* otherwise, integer seconds only? */
			}
			else if (tm->tm_sec != 0)
			{
				is_before |= (tm->tm_sec < 0);
				sprintf(cp, ":%02d", abs(tm->tm_sec));
				cp += strlen(cp);
4346
				is_nonzero = TRUE;
4347 4348
			}
			break;
4349

4350 4351
		case USE_POSTGRES_DATES:
		default:
4352
			if (tm->tm_mday != 0)
4353
			{
4354
				is_before |= (tm->tm_mday < 0);
4355
				sprintf(cp, "%s%d day%s", (is_nonzero ? " " : ""),
4356 4357
				 abs(tm->tm_mday), ((abs(tm->tm_mday) != 1) ? "s" : ""));
				cp += strlen(cp);
4358
				is_nonzero = TRUE;
4359 4360 4361
			}
			if (tm->tm_hour != 0)
			{
4362
				is_before |= (tm->tm_hour < 0);
4363
				sprintf(cp, "%s%d hour%s", (is_nonzero ? " " : ""),
4364
				 abs(tm->tm_hour), ((abs(tm->tm_hour) != 1) ? "s" : ""));
4365
				cp += strlen(cp);
4366
				is_nonzero = TRUE;
4367
			}
4368

4369 4370 4371
			if (tm->tm_min != 0)
			{
				is_before |= (tm->tm_min < 0);
4372 4373
				sprintf(cp, "%s%d min%s", (is_nonzero ? " " : ""),
				   abs(tm->tm_min), ((abs(tm->tm_min) != 1) ? "s" : ""));
4374
				cp += strlen(cp);
4375
				is_nonzero = TRUE;
4376 4377 4378 4379 4380 4381 4382
			}

			/* fractional seconds? */
			if (fsec != 0)
			{
				fsec += tm->tm_sec;
				is_before |= (fsec < 0);
4383
				sprintf(cp, "%s%.2f secs", (is_nonzero ? " " : ""), fabs(fsec));
4384
				cp += strlen(cp);
4385
				is_nonzero = TRUE;
4386 4387 4388 4389 4390 4391

				/* otherwise, integer seconds only? */
			}
			else if (tm->tm_sec != 0)
			{
				is_before |= (tm->tm_sec < 0);
4392 4393
				sprintf(cp, "%s%d sec%s", (is_nonzero ? " " : ""),
				   abs(tm->tm_sec), ((abs(tm->tm_sec) != 1) ? "s" : ""));
4394
				cp += strlen(cp);
4395
				is_nonzero = TRUE;
4396 4397
			}
			break;
4398 4399 4400 4401 4402
	}

	/* identically zero? then put in a unitless zero... */
	if (!is_nonzero)
	{
4403
		strcat(cp, "0");
4404 4405 4406 4407 4408 4409 4410 4411 4412 4413 4414 4415 4416 4417
		cp += strlen(cp);
	}

	if (is_before)
	{
		strcat(cp, " ago");
		cp += strlen(cp);
	}

#ifdef DATEDEBUG
	printf("EncodeTimeSpan- result is %s\n", str);
#endif

	return 0;
4418
}	/* EncodeTimeSpan() */
4419 4420 4421


#if defined(linux) && defined(PPC)
4422 4423
int
datetime_is_epoch(double j)
4424
{
4425 4426
	static union
	{
4427 4428 4429
		double		epoch;
		unsigned char c[8];
	}			u;
4430

4431 4432
	u.c[0] = 0x80;				/* sign bit */
	u.c[1] = 0x10;				/* DBL_MIN */
4433

4434
	return j == u.epoch;
4435
}
4436 4437
int
datetime_is_current(double j)
4438
{
4439 4440
	static union
	{
4441 4442 4443
		double		current;
		unsigned char c[8];
	}			u;
4444

4445
	u.c[1] = 0x10;				/* DBL_MIN */
4446

4447
	return j == u.current;
4448
}
4449

4450
#endif