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