xref: /sqlite-3.40.0/src/date.c (revision 5d00d0a8)
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.107 2009/05/03 20:23:53 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   int isRealNum;    /* Return from sqlite3IsNumber().  Not used */
348   if( parseYyyyMmDd(zDate,p)==0 ){
349     return 0;
350   }else if( parseHhMmSs(zDate, p)==0 ){
351     return 0;
352   }else if( sqlite3StrICmp(zDate,"now")==0){
353     setDateTimeToCurrent(context, p);
354     return 0;
355   }else if( sqlite3IsNumber(zDate, &isRealNum, SQLITE_UTF8) ){
356     double r;
357     getValue(zDate, &r);
358     p->iJD = (sqlite3_int64)(r*86400000.0 + 0.5);
359     p->validJD = 1;
360     return 0;
361   }
362   return 1;
363 }
364 
365 /*
366 ** Compute the Year, Month, and Day from the julian day number.
367 */
368 static void computeYMD(DateTime *p){
369   int Z, A, B, C, D, E, X1;
370   if( p->validYMD ) return;
371   if( !p->validJD ){
372     p->Y = 2000;
373     p->M = 1;
374     p->D = 1;
375   }else{
376     Z = (int)((p->iJD + 43200000)/86400000);
377     A = (int)((Z - 1867216.25)/36524.25);
378     A = Z + 1 + A - (A/4);
379     B = A + 1524;
380     C = (int)((B - 122.1)/365.25);
381     D = (36525*C)/100;
382     E = (int)((B-D)/30.6001);
383     X1 = (int)(30.6001*E);
384     p->D = B - D - X1;
385     p->M = E<14 ? E-1 : E-13;
386     p->Y = p->M>2 ? C - 4716 : C - 4715;
387   }
388   p->validYMD = 1;
389 }
390 
391 /*
392 ** Compute the Hour, Minute, and Seconds from the julian day number.
393 */
394 static void computeHMS(DateTime *p){
395   int s;
396   if( p->validHMS ) return;
397   computeJD(p);
398   s = (int)((p->iJD + 43200000) % 86400000);
399   p->s = s/1000.0;
400   s = (int)p->s;
401   p->s -= s;
402   p->h = s/3600;
403   s -= p->h*3600;
404   p->m = s/60;
405   p->s += s - p->m*60;
406   p->validHMS = 1;
407 }
408 
409 /*
410 ** Compute both YMD and HMS
411 */
412 static void computeYMD_HMS(DateTime *p){
413   computeYMD(p);
414   computeHMS(p);
415 }
416 
417 /*
418 ** Clear the YMD and HMS and the TZ
419 */
420 static void clearYMD_HMS_TZ(DateTime *p){
421   p->validYMD = 0;
422   p->validHMS = 0;
423   p->validTZ = 0;
424 }
425 
426 #ifndef SQLITE_OMIT_LOCALTIME
427 /*
428 ** Compute the difference (in milliseconds)
429 ** between localtime and UTC (a.k.a. GMT)
430 ** for the time value p where p is in UTC.
431 */
432 static sqlite3_int64 localtimeOffset(DateTime *p){
433   DateTime x, y;
434   time_t t;
435   x = *p;
436   computeYMD_HMS(&x);
437   if( x.Y<1971 || x.Y>=2038 ){
438     x.Y = 2000;
439     x.M = 1;
440     x.D = 1;
441     x.h = 0;
442     x.m = 0;
443     x.s = 0.0;
444   } else {
445     int s = (int)(x.s + 0.5);
446     x.s = s;
447   }
448   x.tz = 0;
449   x.validJD = 0;
450   computeJD(&x);
451   t = x.iJD/1000 - 21086676*(i64)10000;
452 #ifdef HAVE_LOCALTIME_R
453   {
454     struct tm sLocal;
455     localtime_r(&t, &sLocal);
456     y.Y = sLocal.tm_year + 1900;
457     y.M = sLocal.tm_mon + 1;
458     y.D = sLocal.tm_mday;
459     y.h = sLocal.tm_hour;
460     y.m = sLocal.tm_min;
461     y.s = sLocal.tm_sec;
462   }
463 #elif defined(HAVE_LOCALTIME_S)
464   {
465     struct tm sLocal;
466     localtime_s(&sLocal, &t);
467     y.Y = sLocal.tm_year + 1900;
468     y.M = sLocal.tm_mon + 1;
469     y.D = sLocal.tm_mday;
470     y.h = sLocal.tm_hour;
471     y.m = sLocal.tm_min;
472     y.s = sLocal.tm_sec;
473   }
474 #else
475   {
476     struct tm *pTm;
477     sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
478     pTm = localtime(&t);
479     y.Y = pTm->tm_year + 1900;
480     y.M = pTm->tm_mon + 1;
481     y.D = pTm->tm_mday;
482     y.h = pTm->tm_hour;
483     y.m = pTm->tm_min;
484     y.s = pTm->tm_sec;
485     sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
486   }
487 #endif
488   y.validYMD = 1;
489   y.validHMS = 1;
490   y.validJD = 0;
491   y.validTZ = 0;
492   computeJD(&y);
493   return y.iJD - x.iJD;
494 }
495 #endif /* SQLITE_OMIT_LOCALTIME */
496 
497 /*
498 ** Process a modifier to a date-time stamp.  The modifiers are
499 ** as follows:
500 **
501 **     NNN days
502 **     NNN hours
503 **     NNN minutes
504 **     NNN.NNNN seconds
505 **     NNN months
506 **     NNN years
507 **     start of month
508 **     start of year
509 **     start of week
510 **     start of day
511 **     weekday N
512 **     unixepoch
513 **     localtime
514 **     utc
515 **
516 ** Return 0 on success and 1 if there is any kind of error.
517 */
518 static int parseModifier(const char *zMod, DateTime *p){
519   int rc = 1;
520   int n;
521   double r;
522   char *z, zBuf[30];
523   z = zBuf;
524   for(n=0; n<ArraySize(zBuf)-1 && zMod[n]; n++){
525     z[n] = (char)sqlite3UpperToLower[(u8)zMod[n]];
526   }
527   z[n] = 0;
528   switch( z[0] ){
529 #ifndef SQLITE_OMIT_LOCALTIME
530     case 'l': {
531       /*    localtime
532       **
533       ** Assuming the current time value is UTC (a.k.a. GMT), shift it to
534       ** show local time.
535       */
536       if( strcmp(z, "localtime")==0 ){
537         computeJD(p);
538         p->iJD += localtimeOffset(p);
539         clearYMD_HMS_TZ(p);
540         rc = 0;
541       }
542       break;
543     }
544 #endif
545     case 'u': {
546       /*
547       **    unixepoch
548       **
549       ** Treat the current value of p->iJD as the number of
550       ** seconds since 1970.  Convert to a real julian day number.
551       */
552       if( strcmp(z, "unixepoch")==0 && p->validJD ){
553         p->iJD = (p->iJD + 43200)/86400 + 21086676*(i64)10000000;
554         clearYMD_HMS_TZ(p);
555         rc = 0;
556       }
557 #ifndef SQLITE_OMIT_LOCALTIME
558       else if( strcmp(z, "utc")==0 ){
559         sqlite3_int64 c1;
560         computeJD(p);
561         c1 = localtimeOffset(p);
562         p->iJD -= c1;
563         clearYMD_HMS_TZ(p);
564         p->iJD += c1 - localtimeOffset(p);
565         rc = 0;
566       }
567 #endif
568       break;
569     }
570     case 'w': {
571       /*
572       **    weekday N
573       **
574       ** Move the date to the same time on the next occurrence of
575       ** weekday N where 0==Sunday, 1==Monday, and so forth.  If the
576       ** date is already on the appropriate weekday, this is a no-op.
577       */
578       if( strncmp(z, "weekday ", 8)==0 && getValue(&z[8],&r)>0
579                  && (n=(int)r)==r && n>=0 && r<7 ){
580         sqlite3_int64 Z;
581         computeYMD_HMS(p);
582         p->validTZ = 0;
583         p->validJD = 0;
584         computeJD(p);
585         Z = ((p->iJD + 129600000)/86400000) % 7;
586         if( Z>n ) Z -= 7;
587         p->iJD += (n - Z)*86400000;
588         clearYMD_HMS_TZ(p);
589         rc = 0;
590       }
591       break;
592     }
593     case 's': {
594       /*
595       **    start of TTTTT
596       **
597       ** Move the date backwards to the beginning of the current day,
598       ** or month or year.
599       */
600       if( strncmp(z, "start of ", 9)!=0 ) break;
601       z += 9;
602       computeYMD(p);
603       p->validHMS = 1;
604       p->h = p->m = 0;
605       p->s = 0.0;
606       p->validTZ = 0;
607       p->validJD = 0;
608       if( strcmp(z,"month")==0 ){
609         p->D = 1;
610         rc = 0;
611       }else if( strcmp(z,"year")==0 ){
612         computeYMD(p);
613         p->M = 1;
614         p->D = 1;
615         rc = 0;
616       }else if( strcmp(z,"day")==0 ){
617         rc = 0;
618       }
619       break;
620     }
621     case '+':
622     case '-':
623     case '0':
624     case '1':
625     case '2':
626     case '3':
627     case '4':
628     case '5':
629     case '6':
630     case '7':
631     case '8':
632     case '9': {
633       double rRounder;
634       n = getValue(z, &r);
635       assert( n>=1 );
636       if( z[n]==':' ){
637         /* A modifier of the form (+|-)HH:MM:SS.FFF adds (or subtracts) the
638         ** specified number of hours, minutes, seconds, and fractional seconds
639         ** to the time.  The ".FFF" may be omitted.  The ":SS.FFF" may be
640         ** omitted.
641         */
642         const char *z2 = z;
643         DateTime tx;
644         sqlite3_int64 day;
645         if( !sqlite3Isdigit(*z2) ) z2++;
646         memset(&tx, 0, sizeof(tx));
647         if( parseHhMmSs(z2, &tx) ) break;
648         computeJD(&tx);
649         tx.iJD -= 43200000;
650         day = tx.iJD/86400000;
651         tx.iJD -= day*86400000;
652         if( z[0]=='-' ) tx.iJD = -tx.iJD;
653         computeJD(p);
654         clearYMD_HMS_TZ(p);
655         p->iJD += tx.iJD;
656         rc = 0;
657         break;
658       }
659       z += n;
660       while( sqlite3Isspace(*z) ) z++;
661       n = sqlite3Strlen30(z);
662       if( n>10 || n<3 ) break;
663       if( z[n-1]=='s' ){ z[n-1] = 0; n--; }
664       computeJD(p);
665       rc = 0;
666       rRounder = r<0 ? -0.5 : +0.5;
667       if( n==3 && strcmp(z,"day")==0 ){
668         p->iJD += (sqlite3_int64)(r*86400000.0 + rRounder);
669       }else if( n==4 && strcmp(z,"hour")==0 ){
670         p->iJD += (sqlite3_int64)(r*(86400000.0/24.0) + rRounder);
671       }else if( n==6 && strcmp(z,"minute")==0 ){
672         p->iJD += (sqlite3_int64)(r*(86400000.0/(24.0*60.0)) + rRounder);
673       }else if( n==6 && strcmp(z,"second")==0 ){
674         p->iJD += (sqlite3_int64)(r*(86400000.0/(24.0*60.0*60.0)) + rRounder);
675       }else if( n==5 && strcmp(z,"month")==0 ){
676         int x, y;
677         computeYMD_HMS(p);
678         p->M += (int)r;
679         x = p->M>0 ? (p->M-1)/12 : (p->M-12)/12;
680         p->Y += x;
681         p->M -= x*12;
682         p->validJD = 0;
683         computeJD(p);
684         y = (int)r;
685         if( y!=r ){
686           p->iJD += (sqlite3_int64)((r - y)*30.0*86400000.0 + rRounder);
687         }
688       }else if( n==4 && strcmp(z,"year")==0 ){
689         int y = (int)r;
690         computeYMD_HMS(p);
691         p->Y += y;
692         p->validJD = 0;
693         computeJD(p);
694         if( y!=r ){
695           p->iJD += (sqlite3_int64)((r - y)*365.0*86400000.0 + rRounder);
696         }
697       }else{
698         rc = 1;
699       }
700       clearYMD_HMS_TZ(p);
701       break;
702     }
703     default: {
704       break;
705     }
706   }
707   return rc;
708 }
709 
710 /*
711 ** Process time function arguments.  argv[0] is a date-time stamp.
712 ** argv[1] and following are modifiers.  Parse them all and write
713 ** the resulting time into the DateTime structure p.  Return 0
714 ** on success and 1 if there are any errors.
715 **
716 ** If there are zero parameters (if even argv[0] is undefined)
717 ** then assume a default value of "now" for argv[0].
718 */
719 static int isDate(
720   sqlite3_context *context,
721   int argc,
722   sqlite3_value **argv,
723   DateTime *p
724 ){
725   int i;
726   const unsigned char *z;
727   int eType;
728   memset(p, 0, sizeof(*p));
729   if( argc==0 ){
730     setDateTimeToCurrent(context, p);
731   }else if( (eType = sqlite3_value_type(argv[0]))==SQLITE_FLOAT
732                    || eType==SQLITE_INTEGER ){
733     p->iJD = (sqlite3_int64)(sqlite3_value_double(argv[0])*86400000.0 + 0.5);
734     p->validJD = 1;
735   }else{
736     z = sqlite3_value_text(argv[0]);
737     if( !z || parseDateOrTime(context, (char*)z, p) ){
738       return 1;
739     }
740   }
741   for(i=1; i<argc; i++){
742     if( (z = sqlite3_value_text(argv[i]))==0 || parseModifier((char*)z, p) ){
743       return 1;
744     }
745   }
746   return 0;
747 }
748 
749 
750 /*
751 ** The following routines implement the various date and time functions
752 ** of SQLite.
753 */
754 
755 /*
756 **    julianday( TIMESTRING, MOD, MOD, ...)
757 **
758 ** Return the julian day number of the date specified in the arguments
759 */
760 static void juliandayFunc(
761   sqlite3_context *context,
762   int argc,
763   sqlite3_value **argv
764 ){
765   DateTime x;
766   if( isDate(context, argc, argv, &x)==0 ){
767     computeJD(&x);
768     sqlite3_result_double(context, x.iJD/86400000.0);
769   }
770 }
771 
772 /*
773 **    datetime( TIMESTRING, MOD, MOD, ...)
774 **
775 ** Return YYYY-MM-DD HH:MM:SS
776 */
777 static void datetimeFunc(
778   sqlite3_context *context,
779   int argc,
780   sqlite3_value **argv
781 ){
782   DateTime x;
783   if( isDate(context, argc, argv, &x)==0 ){
784     char zBuf[100];
785     computeYMD_HMS(&x);
786     sqlite3_snprintf(sizeof(zBuf), zBuf, "%04d-%02d-%02d %02d:%02d:%02d",
787                      x.Y, x.M, x.D, x.h, x.m, (int)(x.s));
788     sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
789   }
790 }
791 
792 /*
793 **    time( TIMESTRING, MOD, MOD, ...)
794 **
795 ** Return HH:MM:SS
796 */
797 static void timeFunc(
798   sqlite3_context *context,
799   int argc,
800   sqlite3_value **argv
801 ){
802   DateTime x;
803   if( isDate(context, argc, argv, &x)==0 ){
804     char zBuf[100];
805     computeHMS(&x);
806     sqlite3_snprintf(sizeof(zBuf), zBuf, "%02d:%02d:%02d", x.h, x.m, (int)x.s);
807     sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
808   }
809 }
810 
811 /*
812 **    date( TIMESTRING, MOD, MOD, ...)
813 **
814 ** Return YYYY-MM-DD
815 */
816 static void dateFunc(
817   sqlite3_context *context,
818   int argc,
819   sqlite3_value **argv
820 ){
821   DateTime x;
822   if( isDate(context, argc, argv, &x)==0 ){
823     char zBuf[100];
824     computeYMD(&x);
825     sqlite3_snprintf(sizeof(zBuf), zBuf, "%04d-%02d-%02d", x.Y, x.M, x.D);
826     sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
827   }
828 }
829 
830 /*
831 **    strftime( FORMAT, TIMESTRING, MOD, MOD, ...)
832 **
833 ** Return a string described by FORMAT.  Conversions as follows:
834 **
835 **   %d  day of month
836 **   %f  ** fractional seconds  SS.SSS
837 **   %H  hour 00-24
838 **   %j  day of year 000-366
839 **   %J  ** Julian day number
840 **   %m  month 01-12
841 **   %M  minute 00-59
842 **   %s  seconds since 1970-01-01
843 **   %S  seconds 00-59
844 **   %w  day of week 0-6  sunday==0
845 **   %W  week of year 00-53
846 **   %Y  year 0000-9999
847 **   %%  %
848 */
849 static void strftimeFunc(
850   sqlite3_context *context,
851   int argc,
852   sqlite3_value **argv
853 ){
854   DateTime x;
855   u64 n;
856   size_t i,j;
857   char *z;
858   sqlite3 *db;
859   const char *zFmt = (const char*)sqlite3_value_text(argv[0]);
860   char zBuf[100];
861   if( zFmt==0 || isDate(context, argc-1, argv+1, &x) ) return;
862   db = sqlite3_context_db_handle(context);
863   for(i=0, n=1; zFmt[i]; i++, n++){
864     if( zFmt[i]=='%' ){
865       switch( zFmt[i+1] ){
866         case 'd':
867         case 'H':
868         case 'm':
869         case 'M':
870         case 'S':
871         case 'W':
872           n++;
873           /* fall thru */
874         case 'w':
875         case '%':
876           break;
877         case 'f':
878           n += 8;
879           break;
880         case 'j':
881           n += 3;
882           break;
883         case 'Y':
884           n += 8;
885           break;
886         case 's':
887         case 'J':
888           n += 50;
889           break;
890         default:
891           return;  /* ERROR.  return a NULL */
892       }
893       i++;
894     }
895   }
896   testcase( n==sizeof(zBuf)-1 );
897   testcase( n==sizeof(zBuf) );
898   testcase( n==(u64)db->aLimit[SQLITE_LIMIT_LENGTH]+1 );
899   testcase( n==(u64)db->aLimit[SQLITE_LIMIT_LENGTH] );
900   if( n<sizeof(zBuf) ){
901     z = zBuf;
902   }else if( n>(u64)db->aLimit[SQLITE_LIMIT_LENGTH] ){
903     sqlite3_result_error_toobig(context);
904     return;
905   }else{
906     z = sqlite3DbMallocRaw(db, (int)n);
907     if( z==0 ){
908       sqlite3_result_error_nomem(context);
909       return;
910     }
911   }
912   computeJD(&x);
913   computeYMD_HMS(&x);
914   for(i=j=0; zFmt[i]; i++){
915     if( zFmt[i]!='%' ){
916       z[j++] = zFmt[i];
917     }else{
918       i++;
919       switch( zFmt[i] ){
920         case 'd':  sqlite3_snprintf(3, &z[j],"%02d",x.D); j+=2; break;
921         case 'f': {
922           double s = x.s;
923           if( s>59.999 ) s = 59.999;
924           sqlite3_snprintf(7, &z[j],"%06.3f", s);
925           j += sqlite3Strlen30(&z[j]);
926           break;
927         }
928         case 'H':  sqlite3_snprintf(3, &z[j],"%02d",x.h); j+=2; break;
929         case 'W': /* Fall thru */
930         case 'j': {
931           int nDay;             /* Number of days since 1st day of year */
932           DateTime y = x;
933           y.validJD = 0;
934           y.M = 1;
935           y.D = 1;
936           computeJD(&y);
937           nDay = (int)((x.iJD-y.iJD+43200000)/86400000);
938           if( zFmt[i]=='W' ){
939             int wd;   /* 0=Monday, 1=Tuesday, ... 6=Sunday */
940             wd = (int)(((x.iJD+43200000)/86400000)%7);
941             sqlite3_snprintf(3, &z[j],"%02d",(nDay+7-wd)/7);
942             j += 2;
943           }else{
944             sqlite3_snprintf(4, &z[j],"%03d",nDay+1);
945             j += 3;
946           }
947           break;
948         }
949         case 'J': {
950           sqlite3_snprintf(20, &z[j],"%.16g",x.iJD/86400000.0);
951           j+=sqlite3Strlen30(&z[j]);
952           break;
953         }
954         case 'm':  sqlite3_snprintf(3, &z[j],"%02d",x.M); j+=2; break;
955         case 'M':  sqlite3_snprintf(3, &z[j],"%02d",x.m); j+=2; break;
956         case 's': {
957           sqlite3_snprintf(30,&z[j],"%lld",
958                            (i64)(x.iJD/1000 - 21086676*(i64)10000));
959           j += sqlite3Strlen30(&z[j]);
960           break;
961         }
962         case 'S':  sqlite3_snprintf(3,&z[j],"%02d",(int)x.s); j+=2; break;
963         case 'w': {
964           z[j++] = (char)(((x.iJD+129600000)/86400000) % 7) + '0';
965           break;
966         }
967         case 'Y': {
968           sqlite3_snprintf(5,&z[j],"%04d",x.Y); j+=sqlite3Strlen30(&z[j]);
969           break;
970         }
971         default:   z[j++] = '%'; break;
972       }
973     }
974   }
975   z[j] = 0;
976   sqlite3_result_text(context, z, -1,
977                       z==zBuf ? SQLITE_TRANSIENT : SQLITE_DYNAMIC);
978 }
979 
980 /*
981 ** current_time()
982 **
983 ** This function returns the same value as time('now').
984 */
985 static void ctimeFunc(
986   sqlite3_context *context,
987   int NotUsed,
988   sqlite3_value **NotUsed2
989 ){
990   UNUSED_PARAMETER2(NotUsed, NotUsed2);
991   timeFunc(context, 0, 0);
992 }
993 
994 /*
995 ** current_date()
996 **
997 ** This function returns the same value as date('now').
998 */
999 static void cdateFunc(
1000   sqlite3_context *context,
1001   int NotUsed,
1002   sqlite3_value **NotUsed2
1003 ){
1004   UNUSED_PARAMETER2(NotUsed, NotUsed2);
1005   dateFunc(context, 0, 0);
1006 }
1007 
1008 /*
1009 ** current_timestamp()
1010 **
1011 ** This function returns the same value as datetime('now').
1012 */
1013 static void ctimestampFunc(
1014   sqlite3_context *context,
1015   int NotUsed,
1016   sqlite3_value **NotUsed2
1017 ){
1018   UNUSED_PARAMETER2(NotUsed, NotUsed2);
1019   datetimeFunc(context, 0, 0);
1020 }
1021 #endif /* !defined(SQLITE_OMIT_DATETIME_FUNCS) */
1022 
1023 #ifdef SQLITE_OMIT_DATETIME_FUNCS
1024 /*
1025 ** If the library is compiled to omit the full-scale date and time
1026 ** handling (to get a smaller binary), the following minimal version
1027 ** of the functions current_time(), current_date() and current_timestamp()
1028 ** are included instead. This is to support column declarations that
1029 ** include "DEFAULT CURRENT_TIME" etc.
1030 **
1031 ** This function uses the C-library functions time(), gmtime()
1032 ** and strftime(). The format string to pass to strftime() is supplied
1033 ** as the user-data for the function.
1034 */
1035 static void currentTimeFunc(
1036   sqlite3_context *context,
1037   int argc,
1038   sqlite3_value **argv
1039 ){
1040   time_t t;
1041   char *zFormat = (char *)sqlite3_user_data(context);
1042   sqlite3 *db;
1043   double rT;
1044   char zBuf[20];
1045 
1046   UNUSED_PARAMETER(argc);
1047   UNUSED_PARAMETER(argv);
1048 
1049   db = sqlite3_context_db_handle(context);
1050   sqlite3OsCurrentTime(db->pVfs, &rT);
1051 #ifndef SQLITE_OMIT_FLOATING_POINT
1052   t = 86400.0*(rT - 2440587.5) + 0.5;
1053 #else
1054   /* without floating point support, rT will have
1055   ** already lost fractional day precision.
1056   */
1057   t = 86400 * (rT - 2440587) - 43200;
1058 #endif
1059 #ifdef HAVE_GMTIME_R
1060   {
1061     struct tm sNow;
1062     gmtime_r(&t, &sNow);
1063     strftime(zBuf, 20, zFormat, &sNow);
1064   }
1065 #else
1066   {
1067     struct tm *pTm;
1068     sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
1069     pTm = gmtime(&t);
1070     strftime(zBuf, 20, zFormat, pTm);
1071     sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
1072   }
1073 #endif
1074 
1075   sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
1076 }
1077 #endif
1078 
1079 /*
1080 ** This function registered all of the above C functions as SQL
1081 ** functions.  This should be the only routine in this file with
1082 ** external linkage.
1083 */
1084 void sqlite3RegisterDateTimeFunctions(void){
1085   static SQLITE_WSD FuncDef aDateTimeFuncs[] = {
1086 #ifndef SQLITE_OMIT_DATETIME_FUNCS
1087     FUNCTION(julianday,        -1, 0, 0, juliandayFunc ),
1088     FUNCTION(date,             -1, 0, 0, dateFunc      ),
1089     FUNCTION(time,             -1, 0, 0, timeFunc      ),
1090     FUNCTION(datetime,         -1, 0, 0, datetimeFunc  ),
1091     FUNCTION(strftime,         -1, 0, 0, strftimeFunc  ),
1092     FUNCTION(current_time,      0, 0, 0, ctimeFunc     ),
1093     FUNCTION(current_timestamp, 0, 0, 0, ctimestampFunc),
1094     FUNCTION(current_date,      0, 0, 0, cdateFunc     ),
1095 #else
1096     STR_FUNCTION(current_time,      0, "%H:%M:%S",          0, currentTimeFunc),
1097     STR_FUNCTION(current_timestamp, 0, "%Y-%m-%d",          0, currentTimeFunc),
1098     STR_FUNCTION(current_date,      0, "%Y-%m-%d %H:%M:%S", 0, currentTimeFunc),
1099 #endif
1100   };
1101   int i;
1102   FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
1103   FuncDef *aFunc = (FuncDef*)&GLOBAL(FuncDef, aDateTimeFuncs);
1104 
1105   for(i=0; i<ArraySize(aDateTimeFuncs); i++){
1106     sqlite3FuncDefInsert(pHash, &aFunc[i]);
1107   }
1108 }
1109