blob: a870359d6af65fb62c3a41b4ec53ed8cb550e42d [file] [log] [blame]
drh7014aff2003-11-01 01:53:53 +00001/*
2** 2003 October 31
3**
4** The author disclaims copyright to this source code. In place of
5** a legal notice, here is a blessing:
6**
7** May you do good and not evil.
8** May you find forgiveness for yourself and forgive others.
9** May you share freely, never taking more than you give.
10**
11*************************************************************************
12** This file contains the C functions that implement date and time
13** functions for SQLite.
14**
15** There is only one exported symbol in this file - the function
16** sqliteRegisterDateTimeFunctions() found at the bottom of the file.
17** All other code has file scope.
18**
19** $Id: date.c,v 1.1 2003/11/01 01:53:54 drh Exp $
20**
21** NOTES:
22**
23** SQLite processes all times and dates as Julian Day numbers. The
24** dates and times are stored as the number of days since noon
25** in Greenwich on November 24, 4714 B.C. according to the Gregorian
26** calendar system.
27**
28** 1970-01-01 00:00:00 is JD 2440587.5
29** 2000-01-01 00:00:00 is JD 2451544.5
30**
31** This implemention requires years to be expressed as a 4-digit number
32** which means that only dates between 0000-01-01 and 9999-12-31 can
33** be represented, even though julian day numbers allow a much wider
34** range of dates.
35**
36** The Gregorian calendar system is used for all dates and times,
37** even those that predate the Gregorian calendar. Historians usually
38** use the Julian calendar for dates prior to 1582-10-15 and for some
39** dates afterwards, depending on locale. Beware of this difference.
40**
41** The conversion algorithms are implemented based on descriptions
42** in the following text:
43**
44** Jean Meeus
45** Astronomical Algorithms, 2nd Edition, 1998
46** ISBM 0-943396-61-1
47** Willmann-Bell, Inc
48** Richmond, Virginia (USA)
49*/
50#ifndef SQLITE_OMIT_DATETIME_FUNCS
51#include <ctype.h>
52#include <stdlib.h>
53#include <assert.h>
54#include "sqliteInt.h"
55#include "os.h"
56
57/*
58** A structure for holding a single date and time.
59*/
60typedef struct DateTime DateTime;
61struct DateTime {
62 double rJD; /* The julian day number */
63 int Y, M, D; /* Year, month, and day */
64 int h, m; /* Hour and minutes */
65 int tz; /* Timezone offset in minutes */
66 double s; /* Seconds */
67 char validYMD; /* True if Y,M,D are valid */
68 char validHMS; /* True if h,m,s are valid */
69 char validJD; /* True if rJD is valid */
70 char validTZ; /* True if tz is valid */
71};
72
73
74/*
75** Convert N digits from zDate into an integer. Return
76** -1 if zDate does not begin with N digits.
77*/
78static int getDigits(const char *zDate, int N){
79 int val = 0;
80 while( N-- ){
81 if( !isdigit(*zDate) ) return -1;
82 val = val*10 + *zDate - '0';
83 zDate++;
84 }
85 return val;
86}
87
88/*
89** Read text from z[] and convert into a floating point number. Return
90** the number of digits converted.
91*/
92static int getValue(const char *z, double *pR){
93 double r = 0.0;
94 double rDivide = 1.0;
95 int isNeg = 0;
96 int nChar = 0;
97 if( *z=='+' ){
98 z++;
99 nChar++;
100 }else if( *z=='-' ){
101 z++;
102 isNeg = 1;
103 nChar++;
104 }
105 if( !isdigit(*z) ) return 0;
106 while( isdigit(*z) ){
107 r = r*10.0 + *z - '0';
108 nChar++;
109 z++;
110 }
111 if( *z=='.' && isdigit(z[1]) ){
112 z++;
113 nChar++;
114 while( isdigit(*z) ){
115 r = r*10.0 + *z - '0';
116 rDivide *= 10.0;
117 nChar++;
118 z++;
119 }
120 r /= rDivide;
121 }
122 if( *z!=0 && !isspace(*z) ) return 0;
123 *pR = isNeg ? -r : r;
124 return nChar;
125}
126
127/*
128** Parse a timezone extension on the end of a date-time.
129** The extension is of the form:
130**
131** (+/-)HH:MM
132**
133** If the parse is successful, write the number of minutes
134** of change in *pnMin and return 0. If a parser error occurs,
135** return 0.
136**
137** A missing specifier is not considered an error.
138*/
139static int parseTimezone(const char *zDate, DateTime *p){
140 int sgn = 0;
141 int nHr, nMn;
142 while( isspace(*zDate) ){ zDate++; }
143 p->tz = 0;
144 if( *zDate=='-' ){
145 sgn = -1;
146 }else if( *zDate=='+' ){
147 sgn = +1;
148 }else{
149 return *zDate!=0;
150 }
151 zDate++;
152 nHr = getDigits(zDate, 2);
153 if( nHr<0 || nHr>14 ) return 1;
154 zDate += 2;
155 if( zDate[0]!=':' ) return 1;
156 zDate++;
157 nMn = getDigits(zDate, 2);
158 if( nMn<0 || nMn>59 ) return 1;
159 zDate += 2;
160 p->tz = sgn*(nMn + nHr*60);
161 while( isspace(*zDate) ){ zDate++; }
162 return *zDate!=0;
163}
164
165/*
166** Parse times of the form HH:MM or HH:MM:SS or HH:MM:SS.FFFF.
167** The HH, MM, and SS must each be exactly 2 digits. The
168** fractional seconds FFFF can be one or more digits.
169**
170** Return 1 if there is a parsing error and 0 on success.
171*/
172static int parseHhMmSs(const char *zDate, DateTime *p){
173 int h, m, s;
174 double ms = 0.0;
175 h = getDigits(zDate, 2);
176 if( h<0 || zDate[2]!=':' ) return 1;
177 zDate += 3;
178 m = getDigits(zDate, 2);
179 if( m<0 || m>59 ) return 1;
180 zDate += 2;
181 if( *zDate==':' ){
182 s = getDigits(&zDate[1], 2);
183 if( s<0 || s>59 ) return 1;
184 zDate += 3;
185 if( *zDate=='.' && isdigit(zDate[1]) ){
186 double rScale = 1.0;
187 zDate++;
188 while( isdigit(*zDate) ){
189 ms = ms*10.0 + *zDate - '0';
190 rScale *= 10.0;
191 zDate++;
192 }
193 ms /= rScale;
194 }
195 }else{
196 s = 0;
197 }
198 p->validJD = 0;
199 p->validHMS = 1;
200 p->h = h;
201 p->m = m;
202 p->s = s + ms;
203 if( parseTimezone(zDate, p) ) return 1;
204 p->validTZ = p->tz!=0;
205 return 0;
206}
207
208/*
209** Convert from YYYY-MM-DD HH:MM:SS to julian day. We always assume
210** that the YYYY-MM-DD is according to the Gregorian calendar.
211**
212** Reference: Meeus page 61
213*/
214static void computeJD(DateTime *p){
215 int Y, M, D, A, B, X1, X2;
216
217 if( p->validJD ) return;
218 if( p->validYMD ){
219 Y = p->Y;
220 M = p->M;
221 D = p->D;
222 }else{
223 Y = 2000;
224 M = 1;
225 D = 1;
226 }
227 if( M<=2 ){
228 Y--;
229 M += 12;
230 }
231 A = Y/100;
232 B = 2 - A + (A/4);
233 X1 = 365.25*(Y+4716);
234 X2 = 30.6001*(M+1);
235 p->rJD = X1 + X2 + D + B - 1524.5;
236 p->validJD = 1;
237 p->validYMD = 0;
238 if( p->validHMS ){
239 p->rJD += (p->h*3600.0 + p->m*60.0 + p->s)/86400.0;
240 if( p->validTZ ){
241 p->rJD += p->tz*60/86400.0;
242 p->validHMS = 0;
243 p->validTZ = 0;
244 }
245 }
246}
247
248/*
249** Parse dates of the form
250**
251** YYYY-MM-DD HH:MM:SS.FFF
252** YYYY-MM-DD HH:MM:SS
253** YYYY-MM-DD HH:MM
254** YYYY-MM-DD
255**
256** Write the result into the DateTime structure and return 0
257** on success and 1 if the input string is not a well-formed
258** date.
259*/
260static int parseYyyyMmDd(const char *zDate, DateTime *p){
261 int Y, M, D;
262
263 Y = getDigits(zDate, 4);
264 if( Y<0 || zDate[4]!='-' ) return 1;
265 zDate += 5;
266 M = getDigits(zDate, 2);
267 if( M<=0 || M>12 || zDate[2]!='-' ) return 1;
268 zDate += 3;
269 D = getDigits(zDate, 2);
270 if( D<=0 || D>31 ) return 1;
271 zDate += 2;
272 while( isspace(*zDate) ){ zDate++; }
273 if( isdigit(*zDate) ){
274 if( parseHhMmSs(zDate, p) ) return 1;
275 }else if( *zDate==0 ){
276 p->validHMS = 0;
277 }else{
278 return 1;
279 }
280 p->validJD = 0;
281 p->validYMD = 1;
282 p->Y = Y;
283 p->M = M;
284 p->D = D;
285 if( p->validTZ ){
286 computeJD(p);
287 }
288 return 0;
289}
290
291/*
292** Attempt to parse the given string into a Julian Day Number. Return
293** the number of errors.
294**
295** The following are acceptable forms for the input string:
296**
297** YYYY-MM-DD HH:MM:SS.FFF +/-HH:MM
298** DDDD.DD
299** now
300**
301** In the first form, the +/-HH:MM is always optional. The fractional
302** seconds extension (the ".FFF") is optional. The seconds portion
303** (":SS.FFF") is option. The year and date can be omitted as long
304** as there is a time string. The time string can be omitted as long
305** as there is a year and date.
306*/
307static int parseDateOrTime(const char *zDate, DateTime *p){
308 int i;
309 memset(p, 0, sizeof(*p));
310 for(i=0; isdigit(zDate[i]); i++){}
311 if( i==4 && zDate[i]=='-' ){
312 return parseYyyyMmDd(zDate, p);
313 }else if( i==2 && zDate[i]==':' ){
314 return parseHhMmSs(zDate, p);
315 return 0;
316 }else if( i==0 && sqliteStrICmp(zDate,"now")==0 ){
317 double r;
318 if( sqliteOsCurrentTime(&r)==0 ){
319 p->rJD = r;
320 p->validJD = 1;
321 return 0;
322 }
323 return 1;
324 }else if( sqliteIsNumber(zDate) ){
325 p->rJD = atof(zDate);
326 p->validJD = 1;
327 return 0;
328 }
329 return 1;
330}
331
332/*
333** Compute the Year, Month, and Day from the julian day number.
334*/
335static void computeYMD(DateTime *p){
336 int Z, A, B, C, D, E, X1;
337 if( p->validYMD ) return;
338 Z = p->rJD + 0.5;
339 A = (Z - 1867216.25)/36524.25;
340 A = Z + 1 + A - (A/4);
341 B = A + 1524;
342 C = (B - 122.1)/365.25;
343 D = 365.25*C;
344 E = (B-D)/30.6001;
345 X1 = 30.6001*E;
346 p->D = B - D - X1;
347 p->M = E<14 ? E-1 : E-13;
348 p->Y = p->M>2 ? C - 4716 : C - 4715;
349 p->validYMD = 1;
350}
351
352/*
353** Compute the Hour, Minute, and Seconds from the julian day number.
354*/
355static void computeHMS(DateTime *p){
356 int Z, s;
357 if( p->validHMS ) return;
358 Z = p->rJD + 0.5;
359 s = (p->rJD + 0.5 - Z)*86400000.0 + 0.5;
360 p->s = 0.001*s;
361 s = p->s;
362 p->s -= s;
363 p->h = s/3600;
364 s -= p->h*3600;
365 p->m = s/60;
366 p->s += s - p->m*60;
367 p->validHMS = 1;
368}
369
370/*
371** Process a modifier to a date-time stamp. The modifiers are
372** as follows:
373**
374** NNN days
375** NNN hours
376** NNN minutes
377** NNN.NNNN seconds
378** NNN months
379** NNN years
380** start of month
381** start of year
382** start of week
383** start of day
384** weekday N
385** unixepoch
386**
387** Return 0 on success and 1 if there is any kind of error.
388*/
389static int parseModifier(const char *zMod, DateTime *p){
390 int rc = 1;
391 int n;
392 double r;
393 char z[30];
394 for(n=0; n<sizeof(z)-1; n++){
395 z[n] = tolower(zMod[n]);
396 }
397 z[n] = 0;
398 switch( z[0] ){
399 case 'u': {
400 /*
401 ** unixepoch
402 **
403 ** Treat the current value of p->rJD as the number of
404 ** seconds since 1970. Convert to a real julian day number.
405 */
406 if( strcmp(z, "unixepoch")==0 && p->validJD ){
407 p->rJD = p->rJD/86400.0 + 2440587.5;
408 p->validYMD = 0;
409 p->validHMS = 0;
410 p->validTZ = 0;
411 rc = 0;
412 }
413 break;
414 }
415 case 'w': {
416 /*
417 ** weekday N
418 **
419 ** Move the date to the beginning of the next occurrance of
420 ** weekday N where 0==Sunday, 1==Monday, and so forth. If the
421 ** date is already on the appropriate weekday, this is equivalent
422 ** to "start of day".
423 */
424 if( strncmp(z, "weekday ", 8)==0 && getValue(&z[8],&r)>0
425 && (n=r)==r && n>=0 && r<7 ){
426 int Z;
427 computeYMD(p);
428 p->validHMS = 0;
429 p->validTZ = 0;
430 p->validJD = 0;
431 computeJD(p);
432 Z = p->rJD + 1.5;
433 Z %= 7;
434 if( Z>n ) Z -= 7;
435 p->rJD += n - Z;
436 p->validYMD = 0;
437 p->validHMS = 0;
438 rc = 0;
439 }
440 break;
441 }
442 case 's': {
443 /*
444 ** start of TTTTT
445 **
446 ** Move the date backwards to the beginning of the current day,
447 ** or month or year.
448 */
449 if( strncmp(z, "start of ", 9)!=0 ) break;
450 zMod = &z[9];
451 computeYMD(p);
452 p->validHMS = 1;
453 p->h = p->m = 0;
454 p->s = 0.0;
455 p->validTZ = 0;
456 p->validJD = 0;
457 if( strcmp(zMod,"month")==0 ){
458 p->D = 1;
459 rc = 0;
460 }else if( strcmp(zMod,"year")==0 ){
461 computeYMD(p);
462 p->M = 1;
463 p->D = 1;
464 rc = 0;
465 }else if( strcmp(zMod,"day")==0 ){
466 rc = 0;
467 }
468 break;
469 }
470 case '+':
471 case '-':
472 case '0':
473 case '1':
474 case '2':
475 case '3':
476 case '4':
477 case '5':
478 case '6':
479 case '7':
480 case '8':
481 case '9': {
482 n = getValue(z, &r);
483 if( n<=0 ) break;
484 zMod = &z[n];
485 while( isspace(zMod[0]) ) zMod++;
486 n = strlen(zMod);
487 if( n>10 || n<3 ) break;
488 strcpy(z, zMod);
489 if( z[n-1]=='s' ){ z[n-1] = 0; n--; }
490 computeJD(p);
491 rc = 0;
492 if( n==3 && strcmp(z,"day")==0 ){
493 p->rJD += r;
494 }else if( n==4 && strcmp(z,"hour")==0 ){
495 computeJD(p);
496 p->rJD += r/24.0;
497 }else if( n==6 && strcmp(z,"minute")==0 ){
498 computeJD(p);
499 p->rJD += r/(24.0*60.0);
500 }else if( n==6 && strcmp(z,"second")==0 ){
501 computeJD(p);
502 p->rJD += r/(24.0*60.0*60.0);
503 }else if( n==5 && strcmp(z,"month")==0 ){
504 int x, y;
505 computeYMD(p);
506 p->M += r;
507 x = p->M>0 ? (p->M-1)/12 : (p->M-12)/12;
508 p->Y += x;
509 p->M -= x*12;
510 p->validJD = 0;
511 computeJD(p);
512 y = r;
513 if( y!=r ){
514 p->rJD += (r - y)*30.0;
515 }
516 }else if( n==4 && strcmp(z,"year")==0 ){
517 computeYMD(p);
518 p->Y += r;
519 p->validJD = 0;
520 computeJD(p);
521 }else{
522 rc = 1;
523 }
524 p->validYMD = 0;
525 p->validHMS = 0;
526 p->validTZ = 0;
527 break;
528 }
529 default: {
530 break;
531 }
532 }
533 return rc;
534}
535
536/*
537** Process time function arguments. argv[0] is a date-time stamp.
538** argv[1] and following are modifiers. Parse them all and write
539** the resulting time into the DateTime structure p. Return 0
540** on success and 1 if there are any errors.
541*/
542static int isDate(int argc, const char **argv, DateTime *p){
543 int i;
544 if( argc==0 ) return 1;
545 if( parseDateOrTime(argv[0], p) ) return 1;
546 for(i=1; i<argc; i++){
547 if( parseModifier(argv[i], p) ) return 1;
548 }
549 return 0;
550}
551
552
553/*
554** The following routines implement the various date and time functions
555** of SQLite.
556*/
557
558/*
559** julianday( TIMESTRING, MOD, MOD, ...)
560**
561** Return the julian day number of the date specified in the arguments
562*/
563static void juliandayFunc(sqlite_func *context, int argc, const char **argv){
564 DateTime x;
565 if( isDate(argc, argv, &x)==0 ){
566 computeJD(&x);
567 sqlite_set_result_double(context, x.rJD);
568 }
569}
570
571/*
572** datetime( TIMESTRING, MOD, MOD, ...)
573**
574** Return YYYY-MM-DD HH:MM:SS
575*/
576static void datetimeFunc(sqlite_func *context, int argc, const char **argv){
577 DateTime x;
578 if( isDate(argc, argv, &x)==0 ){
579 char zBuf[100];
580 computeYMD(&x);
581 computeHMS(&x);
582 sprintf(zBuf, "%04d-%02d-%02d %02d:%02d:%02d",x.Y, x.M, x.D, x.h, x.m,
583 (int)(x.s));
584 sqlite_set_result_string(context, zBuf, -1);
585 }
586}
587
588/*
589** time( TIMESTRING, MOD, MOD, ...)
590**
591** Return HH:MM:SS
592*/
593static void timeFunc(sqlite_func *context, int argc, const char **argv){
594 DateTime x;
595 if( isDate(argc, argv, &x)==0 ){
596 char zBuf[100];
597 computeHMS(&x);
598 sprintf(zBuf, "%02d:%02d:%02d", x.h, x.m, (int)x.s);
599 sqlite_set_result_string(context, zBuf, -1);
600 }
601}
602
603/*
604** date( TIMESTRING, MOD, MOD, ...)
605**
606** Return YYYY-MM-DD
607*/
608static void dateFunc(sqlite_func *context, int argc, const char **argv){
609 DateTime x;
610 if( isDate(argc, argv, &x)==0 ){
611 char zBuf[100];
612 computeYMD(&x);
613 sprintf(zBuf, "%04d-%02d-%02d", x.Y, x.M, x.D);
614 sqlite_set_result_string(context, zBuf, -1);
615 }
616}
617
618/*
619** strftime( FORMAT, TIMESTRING, MOD, MOD, ...)
620**
621** Return a string described by FORMAT. Conversions as follows:
622**
623** %d day of month
624** %f ** fractional seconds SS.SSS
625** %H hour 00-24
626** %j day of year 000-366
627** %J ** Julian day number
628** %m month 01-12
629** %M minute 00-59
630** %s seconds since 1970-01-01
631** %S seconds 00-59
632** %w day of week 0-6 sunday==0
633** %W week of year 00-53
634** %Y year 0000-9999
635** %% %
636*/
637static void strftimeFunc(sqlite_func *context, int argc, const char **argv){
638 DateTime x;
639 int n, i, j;
640 char *z;
641 const char *zFmt = argv[0];
642 char zBuf[100];
643 if( isDate(argc-1, argv+1, &x) ) return;
644 for(i=0, n=1; zFmt[i]; i++, n++){
645 if( zFmt[i]=='%' ){
646 switch( zFmt[i+1] ){
647 case 'd':
648 case 'H':
649 case 'm':
650 case 'M':
651 case 'S':
652 case 'W':
653 n++;
654 /* fall thru */
655 case 'w':
656 case '%':
657 break;
658 case 'f':
659 n += 8;
660 break;
661 case 'j':
662 n += 3;
663 break;
664 case 'Y':
665 n += 8;
666 break;
667 case 's':
668 case 'J':
669 n += 50;
670 break;
671 default:
672 return; /* ERROR. return a NULL */
673 }
674 i++;
675 }
676 }
677 if( n<sizeof(zBuf) ){
678 z = zBuf;
679 }else{
680 z = sqliteMalloc( n );
681 if( z==0 ) return;
682 }
683 computeJD(&x);
684 computeYMD(&x);
685 computeHMS(&x);
686 for(i=j=0; zFmt[i]; i++){
687 if( zFmt[i]!='%' ){
688 z[j++] = zFmt[i];
689 }else{
690 i++;
691 switch( zFmt[i] ){
692 case 'd': sprintf(&z[j],"%02d",x.D); j+=2; break;
693 case 'f': {
694 int s = x.s;
695 int ms = (x.s - s)*1000.0;
696 sprintf(&z[j],"%02d.%03d",s,ms);
697 j += strlen(&z[j]);
698 break;
699 }
700 case 'H': sprintf(&z[j],"%02d",x.h); j+=2; break;
701 case 'W': /* Fall thru */
702 case 'j': {
703 int n;
704 DateTime y = x;
705 y.validJD = 0;
706 y.M = 1;
707 y.D = 1;
708 computeJD(&y);
709 n = x.rJD - y.rJD + 1;
710 if( zFmt[i]=='W' ){
711 sprintf(&z[j],"%02d",(n+6)/7);
712 j += 2;
713 }else{
714 sprintf(&z[j],"%03d",n);
715 j += 3;
716 }
717 break;
718 }
719 case 'J': sprintf(&z[j],"%.16g",x.rJD); j+=strlen(&z[j]); break;
720 case 'm': sprintf(&z[j],"%02d",x.M); j+=2; break;
721 case 'M': sprintf(&z[j],"%02d",x.m); j+=2; break;
722 case 's': {
723 sprintf(&z[j],"%d",(int)((x.rJD-2440587.5)*86400.0));
724 j += strlen(&z[j]);
725 break;
726 }
727 case 'S': sprintf(&z[j],"%02d",(int)x.s); j+=2; break;
728 case 'w': z[j++] = (((int)(x.rJD+1.5)) % 7) + '0'; break;
729 case 'Y': sprintf(&z[j],"%04d",x.Y); j+=strlen(&z[j]); break;
730 case '%': z[j++] = '%'; break;
731 }
732 }
733 }
734 z[j] = 0;
735 sqlite_set_result_string(context, z, -1);
736 if( z!=zBuf ){
737 sqliteFree(z);
738 }
739}
740
741
742#endif /* !defined(SQLITE_OMIT_DATETIME_FUNCS) */
743
744/*
745** This function registered all of the above C functions as SQL
746** functions. This should be the only routine in this file with
747** external linkage.
748*/
749void sqliteRegisterDateTimeFunctions(sqlite *db){
750 static struct {
751 char *zName;
752 int nArg;
753 int dataType;
754 void (*xFunc)(sqlite_func*,int,const char**);
755 } aFuncs[] = {
756#ifndef SQLITE_OMIT_DATETIME_FUNCS
757 { "julianday", -1, SQLITE_NUMERIC, juliandayFunc },
758 { "date", -1, SQLITE_TEXT, dateFunc },
759 { "time", 1, SQLITE_TEXT, timeFunc },
760 { "datetime", -1, SQLITE_TEXT, datetimeFunc },
761 { "strftime", -1, SQLITE_TEXT, strftimeFunc },
762#endif
763 };
764 int i;
765
766 for(i=0; i<sizeof(aFuncs)/sizeof(aFuncs[0]); i++){
767 sqlite_create_function(db, aFuncs[i].zName,
768 aFuncs[i].nArg, aFuncs[i].xFunc, 0);
769 if( aFuncs[i].xFunc ){
770 sqlite_function_type(db, aFuncs[i].zName, aFuncs[i].dataType);
771 }
772 }
773}