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