xref: /sqlite-3.40.0/src/date.c (revision a3f06598)
1 /*
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 ** sqlite3RegisterDateTimeFunctions() found at the bottom of the file.
17 ** All other code has file scope.
18 **
19 ** $Id: date.c,v 1.106 2009/04/16 12:58:03 drh Exp $
20 **
21 ** SQLite processes all times and dates as Julian Day numbers.  The
22 ** dates and times are stored as the number of days since noon
23 ** in Greenwich on November 24, 4714 B.C. according to the Gregorian
24 ** calendar system.
25 **
26 ** 1970-01-01 00:00:00 is JD 2440587.5
27 ** 2000-01-01 00:00:00 is JD 2451544.5
28 **
29 ** This implemention requires years to be expressed as a 4-digit number
30 ** which means that only dates between 0000-01-01 and 9999-12-31 can
31 ** be represented, even though julian day numbers allow a much wider
32 ** range of dates.
33 **
34 ** The Gregorian calendar system is used for all dates and times,
35 ** even those that predate the Gregorian calendar.  Historians usually
36 ** use the Julian calendar for dates prior to 1582-10-15 and for some
37 ** dates afterwards, depending on locale.  Beware of this difference.
38 **
39 ** The conversion algorithms are implemented based on descriptions
40 ** in the following text:
41 **
42 **      Jean Meeus
43 **      Astronomical Algorithms, 2nd Edition, 1998
44 **      ISBM 0-943396-61-1
45 **      Willmann-Bell, Inc
46 **      Richmond, Virginia (USA)
47 */
48 #include "sqliteInt.h"
49 #include <stdlib.h>
50 #include <assert.h>
51 #include <time.h>
52 
53 #ifndef SQLITE_OMIT_DATETIME_FUNCS
54 
55 /*
56 ** On recent Windows platforms, the localtime_s() function is available
57 ** as part of the "Secure CRT". It is essentially equivalent to
58 ** localtime_r() available under most POSIX platforms, except that the
59 ** order of the parameters is reversed.
60 **
61 ** See http://msdn.microsoft.com/en-us/library/a442x3ye(VS.80).aspx.
62 **
63 ** If the user has not indicated to use localtime_r() or localtime_s()
64 ** already, check for an MSVC build environment that provides
65 ** localtime_s().
66 */
67 #if !defined(HAVE_LOCALTIME_R) && !defined(HAVE_LOCALTIME_S) && \
68      defined(_MSC_VER) && defined(_CRT_INSECURE_DEPRECATE)
69 #define HAVE_LOCALTIME_S 1
70 #endif
71 
72 /*
73 ** A structure for holding a single date and time.
74 */
75 typedef struct DateTime DateTime;
76 struct DateTime {
77   sqlite3_int64 iJD; /* The julian day number times 86400000 */
78   int Y, M, D;       /* Year, month, and day */
79   int h, m;          /* Hour and minutes */
80   int tz;            /* Timezone offset in minutes */
81   double s;          /* Seconds */
82   char validYMD;     /* True (1) if Y,M,D are valid */
83   char validHMS;     /* True (1) if h,m,s are valid */
84   char validJD;      /* True (1) if iJD is valid */
85   char validTZ;      /* True (1) if tz is valid */
86 };
87 
88 
89 /*
90 ** Convert zDate into one or more integers.  Additional arguments
91 ** come in groups of 5 as follows:
92 **
93 **       N       number of digits in the integer
94 **       min     minimum allowed value of the integer
95 **       max     maximum allowed value of the integer
96 **       nextC   first character after the integer
97 **       pVal    where to write the integers value.
98 **
99 ** Conversions continue until one with nextC==0 is encountered.
100 ** The function returns the number of successful conversions.
101 */
102 static int getDigits(const char *zDate, ...){
103   va_list ap;
104   int val;
105   int N;
106   int min;
107   int max;
108   int nextC;
109   int *pVal;
110   int cnt = 0;
111   va_start(ap, zDate);
112   do{
113     N = va_arg(ap, int);
114     min = va_arg(ap, int);
115     max = va_arg(ap, int);
116     nextC = va_arg(ap, int);
117     pVal = va_arg(ap, int*);
118     val = 0;
119     while( N-- ){
120       if( !sqlite3Isdigit(*zDate) ){
121         goto end_getDigits;
122       }
123       val = val*10 + *zDate - '0';
124       zDate++;
125     }
126     if( val<min || val>max || (nextC!=0 && nextC!=*zDate) ){
127       goto end_getDigits;
128     }
129     *pVal = val;
130     zDate++;
131     cnt++;
132   }while( nextC );
133 end_getDigits:
134   va_end(ap);
135   return cnt;
136 }
137 
138 /*
139 ** Read text from z[] and convert into a floating point number.  Return
140 ** the number of digits converted.
141 */
142 #define getValue sqlite3AtoF
143 
144 /*
145 ** Parse a timezone extension on the end of a date-time.
146 ** The extension is of the form:
147 **
148 **        (+/-)HH:MM
149 **
150 ** Or the "zulu" notation:
151 **
152 **        Z
153 **
154 ** If the parse is successful, write the number of minutes
155 ** of change in p->tz and return 0.  If a parser error occurs,
156 ** return non-zero.
157 **
158 ** A missing specifier is not considered an error.
159 */
160 static int parseTimezone(const char *zDate, DateTime *p){
161   int sgn = 0;
162   int nHr, nMn;
163   int c;
164   while( sqlite3Isspace(*zDate) ){ zDate++; }
165   p->tz = 0;
166   c = *zDate;
167   if( c=='-' ){
168     sgn = -1;
169   }else if( c=='+' ){
170     sgn = +1;
171   }else if( c=='Z' || c=='z' ){
172     zDate++;
173     goto zulu_time;
174   }else{
175     return c!=0;
176   }
177   zDate++;
178   if( getDigits(zDate, 2, 0, 14, ':', &nHr, 2, 0, 59, 0, &nMn)!=2 ){
179     return 1;
180   }
181   zDate += 5;
182   p->tz = sgn*(nMn + nHr*60);
183 zulu_time:
184   while( sqlite3Isspace(*zDate) ){ zDate++; }
185   return *zDate!=0;
186 }
187 
188 /*
189 ** Parse times of the form HH:MM or HH:MM:SS or HH:MM:SS.FFFF.
190 ** The HH, MM, and SS must each be exactly 2 digits.  The
191 ** fractional seconds FFFF can be one or more digits.
192 **
193 ** Return 1 if there is a parsing error and 0 on success.
194 */
195 static int parseHhMmSs(const char *zDate, DateTime *p){
196   int h, m, s;
197   double ms = 0.0;
198   if( getDigits(zDate, 2, 0, 24, ':', &h, 2, 0, 59, 0, &m)!=2 ){
199     return 1;
200   }
201   zDate += 5;
202   if( *zDate==':' ){
203     zDate++;
204     if( getDigits(zDate, 2, 0, 59, 0, &s)!=1 ){
205       return 1;
206     }
207     zDate += 2;
208     if( *zDate=='.' && sqlite3Isdigit(zDate[1]) ){
209       double rScale = 1.0;
210       zDate++;
211       while( sqlite3Isdigit(*zDate) ){
212         ms = ms*10.0 + *zDate - '0';
213         rScale *= 10.0;
214         zDate++;
215       }
216       ms /= rScale;
217     }
218   }else{
219     s = 0;
220   }
221   p->validJD = 0;
222   p->validHMS = 1;
223   p->h = h;
224   p->m = m;
225   p->s = s + ms;
226   if( parseTimezone(zDate, p) ) return 1;
227   p->validTZ = (p->tz!=0)?1:0;
228   return 0;
229 }
230 
231 /*
232 ** Convert from YYYY-MM-DD HH:MM:SS to julian day.  We always assume
233 ** that the YYYY-MM-DD is according to the Gregorian calendar.
234 **
235 ** Reference:  Meeus page 61
236 */
237 static void computeJD(DateTime *p){
238   int Y, M, D, A, B, X1, X2;
239 
240   if( p->validJD ) return;
241   if( p->validYMD ){
242     Y = p->Y;
243     M = p->M;
244     D = p->D;
245   }else{
246     Y = 2000;  /* If no YMD specified, assume 2000-Jan-01 */
247     M = 1;
248     D = 1;
249   }
250   if( M<=2 ){
251     Y--;
252     M += 12;
253   }
254   A = Y/100;
255   B = 2 - A + (A/4);
256   X1 = 36525*(Y+4716)/100;
257   X2 = 306001*(M+1)/10000;
258   p->iJD = (sqlite3_int64)((X1 + X2 + D + B - 1524.5 ) * 86400000);
259   p->validJD = 1;
260   if( p->validHMS ){
261     p->iJD += p->h*3600000 + p->m*60000 + (sqlite3_int64)(p->s*1000);
262     if( p->validTZ ){
263       p->iJD -= p->tz*60000;
264       p->validYMD = 0;
265       p->validHMS = 0;
266       p->validTZ = 0;
267     }
268   }
269 }
270 
271 /*
272 ** Parse dates of the form
273 **
274 **     YYYY-MM-DD HH:MM:SS.FFF
275 **     YYYY-MM-DD HH:MM:SS
276 **     YYYY-MM-DD HH:MM
277 **     YYYY-MM-DD
278 **
279 ** Write the result into the DateTime structure and return 0
280 ** on success and 1 if the input string is not a well-formed
281 ** date.
282 */
283 static int parseYyyyMmDd(const char *zDate, DateTime *p){
284   int Y, M, D, neg;
285 
286   if( zDate[0]=='-' ){
287     zDate++;
288     neg = 1;
289   }else{
290     neg = 0;
291   }
292   if( getDigits(zDate,4,0,9999,'-',&Y,2,1,12,'-',&M,2,1,31,0,&D)!=3 ){
293     return 1;
294   }
295   zDate += 10;
296   while( sqlite3Isspace(*zDate) || 'T'==*(u8*)zDate ){ zDate++; }
297   if( parseHhMmSs(zDate, p)==0 ){
298     /* We got the time */
299   }else if( *zDate==0 ){
300     p->validHMS = 0;
301   }else{
302     return 1;
303   }
304   p->validJD = 0;
305   p->validYMD = 1;
306   p->Y = neg ? -Y : Y;
307   p->M = M;
308   p->D = D;
309   if( p->validTZ ){
310     computeJD(p);
311   }
312   return 0;
313 }
314 
315 /*
316 ** Set the time to the current time reported by the VFS
317 */
318 static void setDateTimeToCurrent(sqlite3_context *context, DateTime *p){
319   double r;
320   sqlite3 *db = sqlite3_context_db_handle(context);
321   sqlite3OsCurrentTime(db->pVfs, &r);
322   p->iJD = (sqlite3_int64)(r*86400000.0 + 0.5);
323   p->validJD = 1;
324 }
325 
326 /*
327 ** Attempt to parse the given string into a Julian Day Number.  Return
328 ** the number of errors.
329 **
330 ** The following are acceptable forms for the input string:
331 **
332 **      YYYY-MM-DD HH:MM:SS.FFF  +/-HH:MM
333 **      DDDD.DD
334 **      now
335 **
336 ** In the first form, the +/-HH:MM is always optional.  The fractional
337 ** seconds extension (the ".FFF") is optional.  The seconds portion
338 ** (":SS.FFF") is option.  The year and date can be omitted as long
339 ** as there is a time string.  The time string can be omitted as long
340 ** as there is a year and date.
341 */
342 static int parseDateOrTime(
343   sqlite3_context *context,
344   const char *zDate,
345   DateTime *p
346 ){
347   if( parseYyyyMmDd(zDate,p)==0 ){
348     return 0;
349   }else if( parseHhMmSs(zDate, p)==0 ){
350     return 0;
351   }else if( sqlite3StrICmp(zDate,"now")==0){
352     setDateTimeToCurrent(context, p);
353     return 0;
354   }else if( sqlite3IsNumber(zDate, 0, SQLITE_UTF8) ){
355     double r;
356     getValue(zDate, &r);
357     p->iJD = (sqlite3_int64)(r*86400000.0 + 0.5);
358     p->validJD = 1;
359     return 0;
360   }
361   return 1;
362 }
363 
364 /*
365 ** Compute the Year, Month, and Day from the julian day number.
366 */
367 static void computeYMD(DateTime *p){
368   int Z, A, B, C, D, E, X1;
369   if( p->validYMD ) return;
370   if( !p->validJD ){
371     p->Y = 2000;
372     p->M = 1;
373     p->D = 1;
374   }else{
375     Z = (int)((p->iJD + 43200000)/86400000);
376     A = (int)((Z - 1867216.25)/36524.25);
377     A = Z + 1 + A - (A/4);
378     B = A + 1524;
379     C = (int)((B - 122.1)/365.25);
380     D = (36525*C)/100;
381     E = (int)((B-D)/30.6001);
382     X1 = (int)(30.6001*E);
383     p->D = B - D - X1;
384     p->M = E<14 ? E-1 : E-13;
385     p->Y = p->M>2 ? C - 4716 : C - 4715;
386   }
387   p->validYMD = 1;
388 }
389 
390 /*
391 ** Compute the Hour, Minute, and Seconds from the julian day number.
392 */
393 static void computeHMS(DateTime *p){
394   int s;
395   if( p->validHMS ) return;
396   computeJD(p);
397   s = (int)((p->iJD + 43200000) % 86400000);
398   p->s = s/1000.0;
399   s = (int)p->s;
400   p->s -= s;
401   p->h = s/3600;
402   s -= p->h*3600;
403   p->m = s/60;
404   p->s += s - p->m*60;
405   p->validHMS = 1;
406 }
407 
408 /*
409 ** Compute both YMD and HMS
410 */
411 static void computeYMD_HMS(DateTime *p){
412   computeYMD(p);
413   computeHMS(p);
414 }
415 
416 /*
417 ** Clear the YMD and HMS and the TZ
418 */
419 static void clearYMD_HMS_TZ(DateTime *p){
420   p->validYMD = 0;
421   p->validHMS = 0;
422   p->validTZ = 0;
423 }
424 
425 #ifndef SQLITE_OMIT_LOCALTIME
426 /*
427 ** Compute the difference (in milliseconds)
428 ** between localtime and UTC (a.k.a. GMT)
429 ** for the time value p where p is in UTC.
430 */
431 static sqlite3_int64 localtimeOffset(DateTime *p){
432   DateTime x, y;
433   time_t t;
434   x = *p;
435   computeYMD_HMS(&x);
436   if( x.Y<1971 || x.Y>=2038 ){
437     x.Y = 2000;
438     x.M = 1;
439     x.D = 1;
440     x.h = 0;
441     x.m = 0;
442     x.s = 0.0;
443   } else {
444     int s = (int)(x.s + 0.5);
445     x.s = s;
446   }
447   x.tz = 0;
448   x.validJD = 0;
449   computeJD(&x);
450   t = x.iJD/1000 - 21086676*(i64)10000;
451 #ifdef HAVE_LOCALTIME_R
452   {
453     struct tm sLocal;
454     localtime_r(&t, &sLocal);
455     y.Y = sLocal.tm_year + 1900;
456     y.M = sLocal.tm_mon + 1;
457     y.D = sLocal.tm_mday;
458     y.h = sLocal.tm_hour;
459     y.m = sLocal.tm_min;
460     y.s = sLocal.tm_sec;
461   }
462 #elif defined(HAVE_LOCALTIME_S)
463   {
464     struct tm sLocal;
465     localtime_s(&sLocal, &t);
466     y.Y = sLocal.tm_year + 1900;
467     y.M = sLocal.tm_mon + 1;
468     y.D = sLocal.tm_mday;
469     y.h = sLocal.tm_hour;
470     y.m = sLocal.tm_min;
471     y.s = sLocal.tm_sec;
472   }
473 #else
474   {
475     struct tm *pTm;
476     sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
477     pTm = localtime(&t);
478     y.Y = pTm->tm_year + 1900;
479     y.M = pTm->tm_mon + 1;
480     y.D = pTm->tm_mday;
481     y.h = pTm->tm_hour;
482     y.m = pTm->tm_min;
483     y.s = pTm->tm_sec;
484     sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
485   }
486 #endif
487   y.validYMD = 1;
488   y.validHMS = 1;
489   y.validJD = 0;
490   y.validTZ = 0;
491   computeJD(&y);
492   return y.iJD - x.iJD;
493 }
494 #endif /* SQLITE_OMIT_LOCALTIME */
495 
496 /*
497 ** Process a modifier to a date-time stamp.  The modifiers are
498 ** as follows:
499 **
500 **     NNN days
501 **     NNN hours
502 **     NNN minutes
503 **     NNN.NNNN seconds
504 **     NNN months
505 **     NNN years
506 **     start of month
507 **     start of year
508 **     start of week
509 **     start of day
510 **     weekday N
511 **     unixepoch
512 **     localtime
513 **     utc
514 **
515 ** Return 0 on success and 1 if there is any kind of error.
516 */
517 static int parseModifier(const char *zMod, DateTime *p){
518   int rc = 1;
519   int n;
520   double r;
521   char *z, zBuf[30];
522   z = zBuf;
523   for(n=0; n<ArraySize(zBuf)-1 && zMod[n]; n++){
524     z[n] = (char)sqlite3UpperToLower[(u8)zMod[n]];
525   }
526   z[n] = 0;
527   switch( z[0] ){
528 #ifndef SQLITE_OMIT_LOCALTIME
529     case 'l': {
530       /*    localtime
531       **
532       ** Assuming the current time value is UTC (a.k.a. GMT), shift it to
533       ** show local time.
534       */
535       if( strcmp(z, "localtime")==0 ){
536         computeJD(p);
537         p->iJD += localtimeOffset(p);
538         clearYMD_HMS_TZ(p);
539         rc = 0;
540       }
541       break;
542     }
543 #endif
544     case 'u': {
545       /*
546       **    unixepoch
547       **
548       ** Treat the current value of p->iJD as the number of
549       ** seconds since 1970.  Convert to a real julian day number.
550       */
551       if( strcmp(z, "unixepoch")==0 && p->validJD ){
552         p->iJD = (p->iJD + 43200)/86400 + 21086676*(i64)10000000;
553         clearYMD_HMS_TZ(p);
554         rc = 0;
555       }
556 #ifndef SQLITE_OMIT_LOCALTIME
557       else if( strcmp(z, "utc")==0 ){
558         sqlite3_int64 c1;
559         computeJD(p);
560         c1 = localtimeOffset(p);
561         p->iJD -= c1;
562         clearYMD_HMS_TZ(p);
563         p->iJD += c1 - localtimeOffset(p);
564         rc = 0;
565       }
566 #endif
567       break;
568     }
569     case 'w': {
570       /*
571       **    weekday N
572       **
573       ** Move the date to the same time on the next occurrence of
574       ** weekday N where 0==Sunday, 1==Monday, and so forth.  If the
575       ** date is already on the appropriate weekday, this is a no-op.
576       */
577       if( strncmp(z, "weekday ", 8)==0 && getValue(&z[8],&r)>0
578                  && (n=(int)r)==r && n>=0 && r<7 ){
579         sqlite3_int64 Z;
580         computeYMD_HMS(p);
581         p->validTZ = 0;
582         p->validJD = 0;
583         computeJD(p);
584         Z = ((p->iJD + 129600000)/86400000) % 7;
585         if( Z>n ) Z -= 7;
586         p->iJD += (n - Z)*86400000;
587         clearYMD_HMS_TZ(p);
588         rc = 0;
589       }
590       break;
591     }
592     case 's': {
593       /*
594       **    start of TTTTT
595       **
596       ** Move the date backwards to the beginning of the current day,
597       ** or month or year.
598       */
599       if( strncmp(z, "start of ", 9)!=0 ) break;
600       z += 9;
601       computeYMD(p);
602       p->validHMS = 1;
603       p->h = p->m = 0;
604       p->s = 0.0;
605       p->validTZ = 0;
606       p->validJD = 0;
607       if( strcmp(z,"month")==0 ){
608         p->D = 1;
609         rc = 0;
610       }else if( strcmp(z,"year")==0 ){
611         computeYMD(p);
612         p->M = 1;
613         p->D = 1;
614         rc = 0;
615       }else if( strcmp(z,"day")==0 ){
616         rc = 0;
617       }
618       break;
619     }
620     case '+':
621     case '-':
622     case '0':
623     case '1':
624     case '2':
625     case '3':
626     case '4':
627     case '5':
628     case '6':
629     case '7':
630     case '8':
631     case '9': {
632       double rRounder;
633       n = getValue(z, &r);
634       assert( n>=1 );
635       if( z[n]==':' ){
636         /* A modifier of the form (+|-)HH:MM:SS.FFF adds (or subtracts) the
637         ** specified number of hours, minutes, seconds, and fractional seconds
638         ** to the time.  The ".FFF" may be omitted.  The ":SS.FFF" may be
639         ** omitted.
640         */
641         const char *z2 = z;
642         DateTime tx;
643         sqlite3_int64 day;
644         if( !sqlite3Isdigit(*z2) ) z2++;
645         memset(&tx, 0, sizeof(tx));
646         if( parseHhMmSs(z2, &tx) ) break;
647         computeJD(&tx);
648         tx.iJD -= 43200000;
649         day = tx.iJD/86400000;
650         tx.iJD -= day*86400000;
651         if( z[0]=='-' ) tx.iJD = -tx.iJD;
652         computeJD(p);
653         clearYMD_HMS_TZ(p);
654         p->iJD += tx.iJD;
655         rc = 0;
656         break;
657       }
658       z += n;
659       while( sqlite3Isspace(*z) ) z++;
660       n = sqlite3Strlen30(z);
661       if( n>10 || n<3 ) break;
662       if( z[n-1]=='s' ){ z[n-1] = 0; n--; }
663       computeJD(p);
664       rc = 0;
665       rRounder = r<0 ? -0.5 : +0.5;
666       if( n==3 && strcmp(z,"day")==0 ){
667         p->iJD += (sqlite3_int64)(r*86400000.0 + rRounder);
668       }else if( n==4 && strcmp(z,"hour")==0 ){
669         p->iJD += (sqlite3_int64)(r*(86400000.0/24.0) + rRounder);
670       }else if( n==6 && strcmp(z,"minute")==0 ){
671         p->iJD += (sqlite3_int64)(r*(86400000.0/(24.0*60.0)) + rRounder);
672       }else if( n==6 && strcmp(z,"second")==0 ){
673         p->iJD += (sqlite3_int64)(r*(86400000.0/(24.0*60.0*60.0)) + rRounder);
674       }else if( n==5 && strcmp(z,"month")==0 ){
675         int x, y;
676         computeYMD_HMS(p);
677         p->M += (int)r;
678         x = p->M>0 ? (p->M-1)/12 : (p->M-12)/12;
679         p->Y += x;
680         p->M -= x*12;
681         p->validJD = 0;
682         computeJD(p);
683         y = (int)r;
684         if( y!=r ){
685           p->iJD += (sqlite3_int64)((r - y)*30.0*86400000.0 + rRounder);
686         }
687       }else if( n==4 && strcmp(z,"year")==0 ){
688         int y = (int)r;
689         computeYMD_HMS(p);
690         p->Y += y;
691         p->validJD = 0;
692         computeJD(p);
693         if( y!=r ){
694           p->iJD += (sqlite3_int64)((r - y)*365.0*86400000.0 + rRounder);
695         }
696       }else{
697         rc = 1;
698       }
699       clearYMD_HMS_TZ(p);
700       break;
701     }
702     default: {
703       break;
704     }
705   }
706   return rc;
707 }
708 
709 /*
710 ** Process time function arguments.  argv[0] is a date-time stamp.
711 ** argv[1] and following are modifiers.  Parse them all and write
712 ** the resulting time into the DateTime structure p.  Return 0
713 ** on success and 1 if there are any errors.
714 **
715 ** If there are zero parameters (if even argv[0] is undefined)
716 ** then assume a default value of "now" for argv[0].
717 */
718 static int isDate(
719   sqlite3_context *context,
720   int argc,
721   sqlite3_value **argv,
722   DateTime *p
723 ){
724   int i;
725   const unsigned char *z;
726   int eType;
727   memset(p, 0, sizeof(*p));
728   if( argc==0 ){
729     setDateTimeToCurrent(context, p);
730   }else if( (eType = sqlite3_value_type(argv[0]))==SQLITE_FLOAT
731                    || eType==SQLITE_INTEGER ){
732     p->iJD = (sqlite3_int64)(sqlite3_value_double(argv[0])*86400000.0 + 0.5);
733     p->validJD = 1;
734   }else{
735     z = sqlite3_value_text(argv[0]);
736     if( !z || parseDateOrTime(context, (char*)z, p) ){
737       return 1;
738     }
739   }
740   for(i=1; i<argc; i++){
741     if( (z = sqlite3_value_text(argv[i]))==0 || parseModifier((char*)z, p) ){
742       return 1;
743     }
744   }
745   return 0;
746 }
747 
748 
749 /*
750 ** The following routines implement the various date and time functions
751 ** of SQLite.
752 */
753 
754 /*
755 **    julianday( TIMESTRING, MOD, MOD, ...)
756 **
757 ** Return the julian day number of the date specified in the arguments
758 */
759 static void juliandayFunc(
760   sqlite3_context *context,
761   int argc,
762   sqlite3_value **argv
763 ){
764   DateTime x;
765   if( isDate(context, argc, argv, &x)==0 ){
766     computeJD(&x);
767     sqlite3_result_double(context, x.iJD/86400000.0);
768   }
769 }
770 
771 /*
772 **    datetime( TIMESTRING, MOD, MOD, ...)
773 **
774 ** Return YYYY-MM-DD HH:MM:SS
775 */
776 static void datetimeFunc(
777   sqlite3_context *context,
778   int argc,
779   sqlite3_value **argv
780 ){
781   DateTime x;
782   if( isDate(context, argc, argv, &x)==0 ){
783     char zBuf[100];
784     computeYMD_HMS(&x);
785     sqlite3_snprintf(sizeof(zBuf), zBuf, "%04d-%02d-%02d %02d:%02d:%02d",
786                      x.Y, x.M, x.D, x.h, x.m, (int)(x.s));
787     sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
788   }
789 }
790 
791 /*
792 **    time( TIMESTRING, MOD, MOD, ...)
793 **
794 ** Return HH:MM:SS
795 */
796 static void timeFunc(
797   sqlite3_context *context,
798   int argc,
799   sqlite3_value **argv
800 ){
801   DateTime x;
802   if( isDate(context, argc, argv, &x)==0 ){
803     char zBuf[100];
804     computeHMS(&x);
805     sqlite3_snprintf(sizeof(zBuf), zBuf, "%02d:%02d:%02d", x.h, x.m, (int)x.s);
806     sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
807   }
808 }
809 
810 /*
811 **    date( TIMESTRING, MOD, MOD, ...)
812 **
813 ** Return YYYY-MM-DD
814 */
815 static void dateFunc(
816   sqlite3_context *context,
817   int argc,
818   sqlite3_value **argv
819 ){
820   DateTime x;
821   if( isDate(context, argc, argv, &x)==0 ){
822     char zBuf[100];
823     computeYMD(&x);
824     sqlite3_snprintf(sizeof(zBuf), zBuf, "%04d-%02d-%02d", x.Y, x.M, x.D);
825     sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
826   }
827 }
828 
829 /*
830 **    strftime( FORMAT, TIMESTRING, MOD, MOD, ...)
831 **
832 ** Return a string described by FORMAT.  Conversions as follows:
833 **
834 **   %d  day of month
835 **   %f  ** fractional seconds  SS.SSS
836 **   %H  hour 00-24
837 **   %j  day of year 000-366
838 **   %J  ** Julian day number
839 **   %m  month 01-12
840 **   %M  minute 00-59
841 **   %s  seconds since 1970-01-01
842 **   %S  seconds 00-59
843 **   %w  day of week 0-6  sunday==0
844 **   %W  week of year 00-53
845 **   %Y  year 0000-9999
846 **   %%  %
847 */
848 static void strftimeFunc(
849   sqlite3_context *context,
850   int argc,
851   sqlite3_value **argv
852 ){
853   DateTime x;
854   u64 n;
855   size_t i,j;
856   char *z;
857   sqlite3 *db;
858   const char *zFmt = (const char*)sqlite3_value_text(argv[0]);
859   char zBuf[100];
860   if( zFmt==0 || isDate(context, argc-1, argv+1, &x) ) return;
861   db = sqlite3_context_db_handle(context);
862   for(i=0, n=1; zFmt[i]; i++, n++){
863     if( zFmt[i]=='%' ){
864       switch( zFmt[i+1] ){
865         case 'd':
866         case 'H':
867         case 'm':
868         case 'M':
869         case 'S':
870         case 'W':
871           n++;
872           /* fall thru */
873         case 'w':
874         case '%':
875           break;
876         case 'f':
877           n += 8;
878           break;
879         case 'j':
880           n += 3;
881           break;
882         case 'Y':
883           n += 8;
884           break;
885         case 's':
886         case 'J':
887           n += 50;
888           break;
889         default:
890           return;  /* ERROR.  return a NULL */
891       }
892       i++;
893     }
894   }
895   testcase( n==sizeof(zBuf)-1 );
896   testcase( n==sizeof(zBuf) );
897   testcase( n==(u64)db->aLimit[SQLITE_LIMIT_LENGTH]+1 );
898   testcase( n==(u64)db->aLimit[SQLITE_LIMIT_LENGTH] );
899   if( n<sizeof(zBuf) ){
900     z = zBuf;
901   }else if( n>(u64)db->aLimit[SQLITE_LIMIT_LENGTH] ){
902     sqlite3_result_error_toobig(context);
903     return;
904   }else{
905     z = sqlite3DbMallocRaw(db, (int)n);
906     if( z==0 ){
907       sqlite3_result_error_nomem(context);
908       return;
909     }
910   }
911   computeJD(&x);
912   computeYMD_HMS(&x);
913   for(i=j=0; zFmt[i]; i++){
914     if( zFmt[i]!='%' ){
915       z[j++] = zFmt[i];
916     }else{
917       i++;
918       switch( zFmt[i] ){
919         case 'd':  sqlite3_snprintf(3, &z[j],"%02d",x.D); j+=2; break;
920         case 'f': {
921           double s = x.s;
922           if( s>59.999 ) s = 59.999;
923           sqlite3_snprintf(7, &z[j],"%06.3f", s);
924           j += sqlite3Strlen30(&z[j]);
925           break;
926         }
927         case 'H':  sqlite3_snprintf(3, &z[j],"%02d",x.h); j+=2; break;
928         case 'W': /* Fall thru */
929         case 'j': {
930           int nDay;             /* Number of days since 1st day of year */
931           DateTime y = x;
932           y.validJD = 0;
933           y.M = 1;
934           y.D = 1;
935           computeJD(&y);
936           nDay = (int)((x.iJD-y.iJD+43200000)/86400000);
937           if( zFmt[i]=='W' ){
938             int wd;   /* 0=Monday, 1=Tuesday, ... 6=Sunday */
939             wd = (int)(((x.iJD+43200000)/86400000)%7);
940             sqlite3_snprintf(3, &z[j],"%02d",(nDay+7-wd)/7);
941             j += 2;
942           }else{
943             sqlite3_snprintf(4, &z[j],"%03d",nDay+1);
944             j += 3;
945           }
946           break;
947         }
948         case 'J': {
949           sqlite3_snprintf(20, &z[j],"%.16g",x.iJD/86400000.0);
950           j+=sqlite3Strlen30(&z[j]);
951           break;
952         }
953         case 'm':  sqlite3_snprintf(3, &z[j],"%02d",x.M); j+=2; break;
954         case 'M':  sqlite3_snprintf(3, &z[j],"%02d",x.m); j+=2; break;
955         case 's': {
956           sqlite3_snprintf(30,&z[j],"%lld",
957                            (i64)(x.iJD/1000 - 21086676*(i64)10000));
958           j += sqlite3Strlen30(&z[j]);
959           break;
960         }
961         case 'S':  sqlite3_snprintf(3,&z[j],"%02d",(int)x.s); j+=2; break;
962         case 'w': {
963           z[j++] = (char)(((x.iJD+129600000)/86400000) % 7) + '0';
964           break;
965         }
966         case 'Y': {
967           sqlite3_snprintf(5,&z[j],"%04d",x.Y); j+=sqlite3Strlen30(&z[j]);
968           break;
969         }
970         default:   z[j++] = '%'; break;
971       }
972     }
973   }
974   z[j] = 0;
975   sqlite3_result_text(context, z, -1,
976                       z==zBuf ? SQLITE_TRANSIENT : SQLITE_DYNAMIC);
977 }
978 
979 /*
980 ** current_time()
981 **
982 ** This function returns the same value as time('now').
983 */
984 static void ctimeFunc(
985   sqlite3_context *context,
986   int NotUsed,
987   sqlite3_value **NotUsed2
988 ){
989   UNUSED_PARAMETER2(NotUsed, NotUsed2);
990   timeFunc(context, 0, 0);
991 }
992 
993 /*
994 ** current_date()
995 **
996 ** This function returns the same value as date('now').
997 */
998 static void cdateFunc(
999   sqlite3_context *context,
1000   int NotUsed,
1001   sqlite3_value **NotUsed2
1002 ){
1003   UNUSED_PARAMETER2(NotUsed, NotUsed2);
1004   dateFunc(context, 0, 0);
1005 }
1006 
1007 /*
1008 ** current_timestamp()
1009 **
1010 ** This function returns the same value as datetime('now').
1011 */
1012 static void ctimestampFunc(
1013   sqlite3_context *context,
1014   int NotUsed,
1015   sqlite3_value **NotUsed2
1016 ){
1017   UNUSED_PARAMETER2(NotUsed, NotUsed2);
1018   datetimeFunc(context, 0, 0);
1019 }
1020 #endif /* !defined(SQLITE_OMIT_DATETIME_FUNCS) */
1021 
1022 #ifdef SQLITE_OMIT_DATETIME_FUNCS
1023 /*
1024 ** If the library is compiled to omit the full-scale date and time
1025 ** handling (to get a smaller binary), the following minimal version
1026 ** of the functions current_time(), current_date() and current_timestamp()
1027 ** are included instead. This is to support column declarations that
1028 ** include "DEFAULT CURRENT_TIME" etc.
1029 **
1030 ** This function uses the C-library functions time(), gmtime()
1031 ** and strftime(). The format string to pass to strftime() is supplied
1032 ** as the user-data for the function.
1033 */
1034 static void currentTimeFunc(
1035   sqlite3_context *context,
1036   int argc,
1037   sqlite3_value **argv
1038 ){
1039   time_t t;
1040   char *zFormat = (char *)sqlite3_user_data(context);
1041   sqlite3 *db;
1042   double rT;
1043   char zBuf[20];
1044 
1045   UNUSED_PARAMETER(argc);
1046   UNUSED_PARAMETER(argv);
1047 
1048   db = sqlite3_context_db_handle(context);
1049   sqlite3OsCurrentTime(db->pVfs, &rT);
1050 #ifndef SQLITE_OMIT_FLOATING_POINT
1051   t = 86400.0*(rT - 2440587.5) + 0.5;
1052 #else
1053   /* without floating point support, rT will have
1054   ** already lost fractional day precision.
1055   */
1056   t = 86400 * (rT - 2440587) - 43200;
1057 #endif
1058 #ifdef HAVE_GMTIME_R
1059   {
1060     struct tm sNow;
1061     gmtime_r(&t, &sNow);
1062     strftime(zBuf, 20, zFormat, &sNow);
1063   }
1064 #else
1065   {
1066     struct tm *pTm;
1067     sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
1068     pTm = gmtime(&t);
1069     strftime(zBuf, 20, zFormat, pTm);
1070     sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
1071   }
1072 #endif
1073 
1074   sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
1075 }
1076 #endif
1077 
1078 /*
1079 ** This function registered all of the above C functions as SQL
1080 ** functions.  This should be the only routine in this file with
1081 ** external linkage.
1082 */
1083 void sqlite3RegisterDateTimeFunctions(void){
1084   static SQLITE_WSD FuncDef aDateTimeFuncs[] = {
1085 #ifndef SQLITE_OMIT_DATETIME_FUNCS
1086     FUNCTION(julianday,        -1, 0, 0, juliandayFunc ),
1087     FUNCTION(date,             -1, 0, 0, dateFunc      ),
1088     FUNCTION(time,             -1, 0, 0, timeFunc      ),
1089     FUNCTION(datetime,         -1, 0, 0, datetimeFunc  ),
1090     FUNCTION(strftime,         -1, 0, 0, strftimeFunc  ),
1091     FUNCTION(current_time,      0, 0, 0, ctimeFunc     ),
1092     FUNCTION(current_timestamp, 0, 0, 0, ctimestampFunc),
1093     FUNCTION(current_date,      0, 0, 0, cdateFunc     ),
1094 #else
1095     STR_FUNCTION(current_time,      0, "%H:%M:%S",          0, currentTimeFunc),
1096     STR_FUNCTION(current_timestamp, 0, "%Y-%m-%d",          0, currentTimeFunc),
1097     STR_FUNCTION(current_date,      0, "%Y-%m-%d %H:%M:%S", 0, currentTimeFunc),
1098 #endif
1099   };
1100   int i;
1101   FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
1102   FuncDef *aFunc = (FuncDef*)&GLOBAL(FuncDef, aDateTimeFuncs);
1103 
1104   for(i=0; i<ArraySize(aDateTimeFuncs); i++){
1105     sqlite3FuncDefInsert(pHash, &aFunc[i]);
1106   }
1107 }
1108