blob: 4e5e46e0a86a322fad27cb5766468052c9e7f36d [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**
drhc5dd9fa2004-01-07 03:29:16 +000019** $Id: date.c,v 1.7 2004/01/07 03:29:16 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
dougcurrieae534182003-12-24 01:41:19 +000051#include "os.h"
52#include "sqliteInt.h"
drh7014aff2003-11-01 01:53:53 +000053#include <ctype.h>
54#include <stdlib.h>
55#include <assert.h>
drh7091cb02003-12-23 16:22:18 +000056#include <time.h>
drh7014aff2003-11-01 01:53:53 +000057
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];
drh89ef0ee2003-12-31 17:25:47 +0000443 for(n=0; n<sizeof(z)-1 && zMod[n]; n++){
drh7014aff2003-11-01 01:53:53 +0000444 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 **
drhc5dd9fa2004-01-07 03:29:16 +0000497 ** Move the date to the same time on the next occurrance of
drh7014aff2003-11-01 01:53:53 +0000498 ** weekday N where 0==Sunday, 1==Monday, and so forth. If the
drhc5dd9fa2004-01-07 03:29:16 +0000499 ** date is already on the appropriate weekday, this is a no-op.
drh7014aff2003-11-01 01:53:53 +0000500 */
501 if( strncmp(z, "weekday ", 8)==0 && getValue(&z[8],&r)>0
502 && (n=r)==r && n>=0 && r<7 ){
503 int Z;
504 computeYMD(p);
drhc5dd9fa2004-01-07 03:29:16 +0000505 computeHMS(p);
drh7014aff2003-11-01 01:53:53 +0000506 p->validTZ = 0;
507 p->validJD = 0;
508 computeJD(p);
509 Z = p->rJD + 1.5;
510 Z %= 7;
511 if( Z>n ) Z -= 7;
512 p->rJD += n - Z;
513 p->validYMD = 0;
514 p->validHMS = 0;
515 rc = 0;
516 }
517 break;
518 }
519 case 's': {
520 /*
521 ** start of TTTTT
522 **
523 ** Move the date backwards to the beginning of the current day,
524 ** or month or year.
525 */
526 if( strncmp(z, "start of ", 9)!=0 ) break;
527 zMod = &z[9];
528 computeYMD(p);
529 p->validHMS = 1;
530 p->h = p->m = 0;
531 p->s = 0.0;
532 p->validTZ = 0;
533 p->validJD = 0;
534 if( strcmp(zMod,"month")==0 ){
535 p->D = 1;
536 rc = 0;
537 }else if( strcmp(zMod,"year")==0 ){
538 computeYMD(p);
539 p->M = 1;
540 p->D = 1;
541 rc = 0;
542 }else if( strcmp(zMod,"day")==0 ){
543 rc = 0;
544 }
545 break;
546 }
547 case '+':
548 case '-':
549 case '0':
550 case '1':
551 case '2':
552 case '3':
553 case '4':
554 case '5':
555 case '6':
556 case '7':
557 case '8':
558 case '9': {
559 n = getValue(z, &r);
560 if( n<=0 ) break;
561 zMod = &z[n];
562 while( isspace(zMod[0]) ) zMod++;
563 n = strlen(zMod);
564 if( n>10 || n<3 ) break;
565 strcpy(z, zMod);
566 if( z[n-1]=='s' ){ z[n-1] = 0; n--; }
567 computeJD(p);
568 rc = 0;
569 if( n==3 && strcmp(z,"day")==0 ){
570 p->rJD += r;
571 }else if( n==4 && strcmp(z,"hour")==0 ){
572 computeJD(p);
573 p->rJD += r/24.0;
574 }else if( n==6 && strcmp(z,"minute")==0 ){
575 computeJD(p);
576 p->rJD += r/(24.0*60.0);
577 }else if( n==6 && strcmp(z,"second")==0 ){
578 computeJD(p);
579 p->rJD += r/(24.0*60.0*60.0);
580 }else if( n==5 && strcmp(z,"month")==0 ){
581 int x, y;
582 computeYMD(p);
drhc5dd9fa2004-01-07 03:29:16 +0000583 computeHMS(p);
drh7014aff2003-11-01 01:53:53 +0000584 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);
drhc5dd9fa2004-01-07 03:29:16 +0000596 computeHMS(p);
drh7014aff2003-11-01 01:53:53 +0000597 p->Y += r;
598 p->validJD = 0;
599 computeJD(p);
600 }else{
601 rc = 1;
602 }
603 p->validYMD = 0;
604 p->validHMS = 0;
605 p->validTZ = 0;
606 break;
607 }
608 default: {
609 break;
610 }
611 }
612 return rc;
613}
614
615/*
616** Process time function arguments. argv[0] is a date-time stamp.
617** argv[1] and following are modifiers. Parse them all and write
618** the resulting time into the DateTime structure p. Return 0
619** on success and 1 if there are any errors.
620*/
621static int isDate(int argc, const char **argv, DateTime *p){
622 int i;
623 if( argc==0 ) return 1;
drhf586aa82003-12-23 16:34:12 +0000624 if( argv[0]==0 || parseDateOrTime(argv[0], p) ) return 1;
drh7014aff2003-11-01 01:53:53 +0000625 for(i=1; i<argc; i++){
drhf586aa82003-12-23 16:34:12 +0000626 if( argv[i]==0 || parseModifier(argv[i], p) ) return 1;
drh7014aff2003-11-01 01:53:53 +0000627 }
628 return 0;
629}
630
631
632/*
633** The following routines implement the various date and time functions
634** of SQLite.
635*/
636
637/*
638** julianday( TIMESTRING, MOD, MOD, ...)
639**
640** Return the julian day number of the date specified in the arguments
641*/
642static void juliandayFunc(sqlite_func *context, int argc, const char **argv){
643 DateTime x;
644 if( isDate(argc, argv, &x)==0 ){
645 computeJD(&x);
646 sqlite_set_result_double(context, x.rJD);
647 }
648}
649
650/*
651** datetime( TIMESTRING, MOD, MOD, ...)
652**
653** Return YYYY-MM-DD HH:MM:SS
654*/
655static void datetimeFunc(sqlite_func *context, int argc, const char **argv){
656 DateTime x;
657 if( isDate(argc, argv, &x)==0 ){
658 char zBuf[100];
659 computeYMD(&x);
660 computeHMS(&x);
661 sprintf(zBuf, "%04d-%02d-%02d %02d:%02d:%02d",x.Y, x.M, x.D, x.h, x.m,
662 (int)(x.s));
663 sqlite_set_result_string(context, zBuf, -1);
664 }
665}
666
667/*
668** time( TIMESTRING, MOD, MOD, ...)
669**
670** Return HH:MM:SS
671*/
672static void timeFunc(sqlite_func *context, int argc, const char **argv){
673 DateTime x;
674 if( isDate(argc, argv, &x)==0 ){
675 char zBuf[100];
676 computeHMS(&x);
677 sprintf(zBuf, "%02d:%02d:%02d", x.h, x.m, (int)x.s);
678 sqlite_set_result_string(context, zBuf, -1);
679 }
680}
681
682/*
683** date( TIMESTRING, MOD, MOD, ...)
684**
685** Return YYYY-MM-DD
686*/
687static void dateFunc(sqlite_func *context, int argc, const char **argv){
688 DateTime x;
689 if( isDate(argc, argv, &x)==0 ){
690 char zBuf[100];
691 computeYMD(&x);
692 sprintf(zBuf, "%04d-%02d-%02d", x.Y, x.M, x.D);
693 sqlite_set_result_string(context, zBuf, -1);
694 }
695}
696
697/*
698** strftime( FORMAT, TIMESTRING, MOD, MOD, ...)
699**
700** Return a string described by FORMAT. Conversions as follows:
701**
702** %d day of month
703** %f ** fractional seconds SS.SSS
704** %H hour 00-24
705** %j day of year 000-366
706** %J ** Julian day number
707** %m month 01-12
708** %M minute 00-59
709** %s seconds since 1970-01-01
710** %S seconds 00-59
711** %w day of week 0-6 sunday==0
712** %W week of year 00-53
713** %Y year 0000-9999
714** %% %
715*/
716static void strftimeFunc(sqlite_func *context, int argc, const char **argv){
717 DateTime x;
718 int n, i, j;
719 char *z;
720 const char *zFmt = argv[0];
721 char zBuf[100];
drhf586aa82003-12-23 16:34:12 +0000722 if( argv[0]==0 || isDate(argc-1, argv+1, &x) ) return;
drh7014aff2003-11-01 01:53:53 +0000723 for(i=0, n=1; zFmt[i]; i++, n++){
724 if( zFmt[i]=='%' ){
725 switch( zFmt[i+1] ){
726 case 'd':
727 case 'H':
728 case 'm':
729 case 'M':
730 case 'S':
731 case 'W':
732 n++;
733 /* fall thru */
734 case 'w':
735 case '%':
736 break;
737 case 'f':
738 n += 8;
739 break;
740 case 'j':
741 n += 3;
742 break;
743 case 'Y':
744 n += 8;
745 break;
746 case 's':
747 case 'J':
748 n += 50;
749 break;
750 default:
751 return; /* ERROR. return a NULL */
752 }
753 i++;
754 }
755 }
756 if( n<sizeof(zBuf) ){
757 z = zBuf;
758 }else{
759 z = sqliteMalloc( n );
760 if( z==0 ) return;
761 }
762 computeJD(&x);
763 computeYMD(&x);
764 computeHMS(&x);
765 for(i=j=0; zFmt[i]; i++){
766 if( zFmt[i]!='%' ){
767 z[j++] = zFmt[i];
768 }else{
769 i++;
770 switch( zFmt[i] ){
771 case 'd': sprintf(&z[j],"%02d",x.D); j+=2; break;
772 case 'f': {
773 int s = x.s;
774 int ms = (x.s - s)*1000.0;
775 sprintf(&z[j],"%02d.%03d",s,ms);
776 j += strlen(&z[j]);
777 break;
778 }
779 case 'H': sprintf(&z[j],"%02d",x.h); j+=2; break;
780 case 'W': /* Fall thru */
781 case 'j': {
782 int n;
783 DateTime y = x;
784 y.validJD = 0;
785 y.M = 1;
786 y.D = 1;
787 computeJD(&y);
788 n = x.rJD - y.rJD + 1;
789 if( zFmt[i]=='W' ){
790 sprintf(&z[j],"%02d",(n+6)/7);
791 j += 2;
792 }else{
793 sprintf(&z[j],"%03d",n);
794 j += 3;
795 }
796 break;
797 }
798 case 'J': sprintf(&z[j],"%.16g",x.rJD); j+=strlen(&z[j]); break;
799 case 'm': sprintf(&z[j],"%02d",x.M); j+=2; break;
800 case 'M': sprintf(&z[j],"%02d",x.m); j+=2; break;
801 case 's': {
drhc5dd9fa2004-01-07 03:29:16 +0000802 sprintf(&z[j],"%d",(int)((x.rJD-2440587.5)*86400.0 + 0.5));
drh7014aff2003-11-01 01:53:53 +0000803 j += strlen(&z[j]);
804 break;
805 }
drhc5dd9fa2004-01-07 03:29:16 +0000806 case 'S': sprintf(&z[j],"%02d",(int)(x.s+0.5)); j+=2; break;
drh7014aff2003-11-01 01:53:53 +0000807 case 'w': z[j++] = (((int)(x.rJD+1.5)) % 7) + '0'; break;
808 case 'Y': sprintf(&z[j],"%04d",x.Y); j+=strlen(&z[j]); break;
809 case '%': z[j++] = '%'; break;
810 }
811 }
812 }
813 z[j] = 0;
814 sqlite_set_result_string(context, z, -1);
815 if( z!=zBuf ){
816 sqliteFree(z);
817 }
818}
819
820
821#endif /* !defined(SQLITE_OMIT_DATETIME_FUNCS) */
822
823/*
824** This function registered all of the above C functions as SQL
825** functions. This should be the only routine in this file with
826** external linkage.
827*/
828void sqliteRegisterDateTimeFunctions(sqlite *db){
829 static struct {
830 char *zName;
831 int nArg;
832 int dataType;
833 void (*xFunc)(sqlite_func*,int,const char**);
834 } aFuncs[] = {
835#ifndef SQLITE_OMIT_DATETIME_FUNCS
836 { "julianday", -1, SQLITE_NUMERIC, juliandayFunc },
837 { "date", -1, SQLITE_TEXT, dateFunc },
drhf586aa82003-12-23 16:34:12 +0000838 { "time", -1, SQLITE_TEXT, timeFunc },
drh7014aff2003-11-01 01:53:53 +0000839 { "datetime", -1, SQLITE_TEXT, datetimeFunc },
840 { "strftime", -1, SQLITE_TEXT, strftimeFunc },
841#endif
842 };
843 int i;
844
845 for(i=0; i<sizeof(aFuncs)/sizeof(aFuncs[0]); i++){
846 sqlite_create_function(db, aFuncs[i].zName,
847 aFuncs[i].nArg, aFuncs[i].xFunc, 0);
848 if( aFuncs[i].xFunc ){
849 sqlite_function_type(db, aFuncs[i].zName, aFuncs[i].dataType);
850 }
851 }
852}