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