blob: 062b88beb8b67f4f7dcd37a56e9ff3421d07b220 [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**
drh4d5b8362004-01-17 01:16:21 +000019** $Id: date.c,v 1.9 2004/01/17 01:16:21 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{
drhba212562004-01-08 02:17:31 +0000224 Y = 2000; /* If no YMD specified, assume 2000-Jan-01 */
drh7014aff2003-11-01 01:53:53 +0000225 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/*
drhba212562004-01-08 02:17:31 +0000372** Compute both YMD and HMS
373*/
374static void computeYMD_HMS(DateTime *p){
375 computeYMD(p);
376 computeHMS(p);
377}
378
379/*
380** Clear the YMD and HMS and the TZ
381*/
382static void clearYMD_HMS_TZ(DateTime *p){
383 p->validYMD = 0;
384 p->validHMS = 0;
385 p->validTZ = 0;
386}
387
388/*
drh7091cb02003-12-23 16:22:18 +0000389** Compute the difference (in days) between localtime and UTC (a.k.a. GMT)
390** for the time value p where p is in UTC.
391*/
392static double localtimeOffset(DateTime *p){
393 DateTime x, y;
394 time_t t;
395 struct tm *pTm;
drh7091cb02003-12-23 16:22:18 +0000396 x = *p;
drhba212562004-01-08 02:17:31 +0000397 computeYMD_HMS(&x);
drh7091cb02003-12-23 16:22:18 +0000398 if( x.Y<1971 || x.Y>=2038 ){
399 x.Y = 2000;
400 x.M = 1;
401 x.D = 1;
402 x.h = 0;
403 x.m = 0;
404 x.s = 0.0;
405 } else {
406 int s = x.s + 0.5;
407 x.s = s;
408 }
409 x.tz = 0;
410 x.validJD = 0;
411 computeJD(&x);
412 t = (x.rJD-2440587.5)*86400.0 + 0.5;
413 sqliteOsEnterMutex();
414 pTm = localtime(&t);
415 y.Y = pTm->tm_year + 1900;
416 y.M = pTm->tm_mon + 1;
417 y.D = pTm->tm_mday;
418 y.h = pTm->tm_hour;
419 y.m = pTm->tm_min;
420 y.s = pTm->tm_sec;
421 sqliteOsLeaveMutex();
422 y.validYMD = 1;
423 y.validHMS = 1;
424 y.validJD = 0;
425 y.validTZ = 0;
426 computeJD(&y);
drh7091cb02003-12-23 16:22:18 +0000427 return y.rJD - x.rJD;
428}
429
430/*
drh7014aff2003-11-01 01:53:53 +0000431** Process a modifier to a date-time stamp. The modifiers are
432** as follows:
433**
434** NNN days
435** NNN hours
436** NNN minutes
437** NNN.NNNN seconds
438** NNN months
439** NNN years
440** start of month
441** start of year
442** start of week
443** start of day
444** weekday N
445** unixepoch
drh7091cb02003-12-23 16:22:18 +0000446** localtime
447** utc
drh7014aff2003-11-01 01:53:53 +0000448**
449** Return 0 on success and 1 if there is any kind of error.
450*/
451static int parseModifier(const char *zMod, DateTime *p){
452 int rc = 1;
453 int n;
454 double r;
drh4d5b8362004-01-17 01:16:21 +0000455 char *z, zBuf[30];
456 z = zBuf;
457 for(n=0; n<sizeof(zBuf)-1 && zMod[n]; n++){
drh7014aff2003-11-01 01:53:53 +0000458 z[n] = tolower(zMod[n]);
459 }
460 z[n] = 0;
461 switch( z[0] ){
drh7091cb02003-12-23 16:22:18 +0000462 case 'l': {
463 /* localtime
464 **
465 ** Assuming the current time value is UTC (a.k.a. GMT), shift it to
466 ** show local time.
467 */
468 if( strcmp(z, "localtime")==0 ){
469 computeJD(p);
470 p->rJD += localtimeOffset(p);
drhba212562004-01-08 02:17:31 +0000471 clearYMD_HMS_TZ(p);
drh7091cb02003-12-23 16:22:18 +0000472 rc = 0;
473 }
474 break;
475 }
drh7014aff2003-11-01 01:53:53 +0000476 case 'u': {
477 /*
478 ** unixepoch
479 **
480 ** Treat the current value of p->rJD as the number of
481 ** seconds since 1970. Convert to a real julian day number.
482 */
483 if( strcmp(z, "unixepoch")==0 && p->validJD ){
484 p->rJD = p->rJD/86400.0 + 2440587.5;
drhba212562004-01-08 02:17:31 +0000485 clearYMD_HMS_TZ(p);
drh7014aff2003-11-01 01:53:53 +0000486 rc = 0;
drh7091cb02003-12-23 16:22:18 +0000487 }else if( strcmp(z, "utc")==0 ){
488 double c1;
489 computeJD(p);
490 c1 = localtimeOffset(p);
491 p->rJD -= c1;
drhba212562004-01-08 02:17:31 +0000492 clearYMD_HMS_TZ(p);
drh7091cb02003-12-23 16:22:18 +0000493 p->rJD += c1 - localtimeOffset(p);
drh7091cb02003-12-23 16:22:18 +0000494 rc = 0;
drh7014aff2003-11-01 01:53:53 +0000495 }
496 break;
497 }
498 case 'w': {
499 /*
500 ** weekday N
501 **
drhc5dd9fa2004-01-07 03:29:16 +0000502 ** Move the date to the same time on the next occurrance of
drh7014aff2003-11-01 01:53:53 +0000503 ** weekday N where 0==Sunday, 1==Monday, and so forth. If the
drhc5dd9fa2004-01-07 03:29:16 +0000504 ** date is already on the appropriate weekday, this is a no-op.
drh7014aff2003-11-01 01:53:53 +0000505 */
506 if( strncmp(z, "weekday ", 8)==0 && getValue(&z[8],&r)>0
507 && (n=r)==r && n>=0 && r<7 ){
508 int Z;
drhba212562004-01-08 02:17:31 +0000509 computeYMD_HMS(p);
drh7014aff2003-11-01 01:53:53 +0000510 p->validTZ = 0;
511 p->validJD = 0;
512 computeJD(p);
513 Z = p->rJD + 1.5;
514 Z %= 7;
515 if( Z>n ) Z -= 7;
516 p->rJD += n - Z;
drhba212562004-01-08 02:17:31 +0000517 clearYMD_HMS_TZ(p);
drh7014aff2003-11-01 01:53:53 +0000518 rc = 0;
519 }
520 break;
521 }
522 case 's': {
523 /*
524 ** start of TTTTT
525 **
526 ** Move the date backwards to the beginning of the current day,
527 ** or month or year.
528 */
529 if( strncmp(z, "start of ", 9)!=0 ) break;
drh4d5b8362004-01-17 01:16:21 +0000530 z += 9;
drh7014aff2003-11-01 01:53:53 +0000531 computeYMD(p);
532 p->validHMS = 1;
533 p->h = p->m = 0;
534 p->s = 0.0;
535 p->validTZ = 0;
536 p->validJD = 0;
drh4d5b8362004-01-17 01:16:21 +0000537 if( strcmp(z,"month")==0 ){
drh7014aff2003-11-01 01:53:53 +0000538 p->D = 1;
539 rc = 0;
drh4d5b8362004-01-17 01:16:21 +0000540 }else if( strcmp(z,"year")==0 ){
drh7014aff2003-11-01 01:53:53 +0000541 computeYMD(p);
542 p->M = 1;
543 p->D = 1;
544 rc = 0;
drh4d5b8362004-01-17 01:16:21 +0000545 }else if( strcmp(z,"day")==0 ){
drh7014aff2003-11-01 01:53:53 +0000546 rc = 0;
547 }
548 break;
549 }
550 case '+':
551 case '-':
552 case '0':
553 case '1':
554 case '2':
555 case '3':
556 case '4':
557 case '5':
558 case '6':
559 case '7':
560 case '8':
561 case '9': {
562 n = getValue(z, &r);
563 if( n<=0 ) break;
drh4d5b8362004-01-17 01:16:21 +0000564 z += n;
565 while( isspace(z[0]) ) z++;
566 n = strlen(z);
drh7014aff2003-11-01 01:53:53 +0000567 if( n>10 || n<3 ) break;
drh7014aff2003-11-01 01:53:53 +0000568 if( z[n-1]=='s' ){ z[n-1] = 0; n--; }
569 computeJD(p);
570 rc = 0;
571 if( n==3 && strcmp(z,"day")==0 ){
572 p->rJD += r;
573 }else if( n==4 && strcmp(z,"hour")==0 ){
drh7014aff2003-11-01 01:53:53 +0000574 p->rJD += r/24.0;
575 }else if( n==6 && strcmp(z,"minute")==0 ){
drh7014aff2003-11-01 01:53:53 +0000576 p->rJD += r/(24.0*60.0);
577 }else if( n==6 && strcmp(z,"second")==0 ){
drh7014aff2003-11-01 01:53:53 +0000578 p->rJD += r/(24.0*60.0*60.0);
579 }else if( n==5 && strcmp(z,"month")==0 ){
580 int x, y;
drhba212562004-01-08 02:17:31 +0000581 computeYMD_HMS(p);
drh7014aff2003-11-01 01:53:53 +0000582 p->M += r;
583 x = p->M>0 ? (p->M-1)/12 : (p->M-12)/12;
584 p->Y += x;
585 p->M -= x*12;
586 p->validJD = 0;
587 computeJD(p);
588 y = r;
589 if( y!=r ){
590 p->rJD += (r - y)*30.0;
591 }
592 }else if( n==4 && strcmp(z,"year")==0 ){
drhba212562004-01-08 02:17:31 +0000593 computeYMD_HMS(p);
drh7014aff2003-11-01 01:53:53 +0000594 p->Y += r;
595 p->validJD = 0;
596 computeJD(p);
597 }else{
598 rc = 1;
599 }
drhba212562004-01-08 02:17:31 +0000600 clearYMD_HMS_TZ(p);
drh7014aff2003-11-01 01:53:53 +0000601 break;
602 }
603 default: {
604 break;
605 }
606 }
607 return rc;
608}
609
610/*
611** Process time function arguments. argv[0] is a date-time stamp.
612** argv[1] and following are modifiers. Parse them all and write
613** the resulting time into the DateTime structure p. Return 0
614** on success and 1 if there are any errors.
615*/
616static int isDate(int argc, const char **argv, DateTime *p){
617 int i;
618 if( argc==0 ) return 1;
drhf586aa82003-12-23 16:34:12 +0000619 if( argv[0]==0 || parseDateOrTime(argv[0], p) ) return 1;
drh7014aff2003-11-01 01:53:53 +0000620 for(i=1; i<argc; i++){
drhf586aa82003-12-23 16:34:12 +0000621 if( argv[i]==0 || parseModifier(argv[i], p) ) return 1;
drh7014aff2003-11-01 01:53:53 +0000622 }
623 return 0;
624}
625
626
627/*
628** The following routines implement the various date and time functions
629** of SQLite.
630*/
631
632/*
633** julianday( TIMESTRING, MOD, MOD, ...)
634**
635** Return the julian day number of the date specified in the arguments
636*/
637static void juliandayFunc(sqlite_func *context, int argc, const char **argv){
638 DateTime x;
639 if( isDate(argc, argv, &x)==0 ){
640 computeJD(&x);
641 sqlite_set_result_double(context, x.rJD);
642 }
643}
644
645/*
646** datetime( TIMESTRING, MOD, MOD, ...)
647**
648** Return YYYY-MM-DD HH:MM:SS
649*/
650static void datetimeFunc(sqlite_func *context, int argc, const char **argv){
651 DateTime x;
652 if( isDate(argc, argv, &x)==0 ){
653 char zBuf[100];
drhba212562004-01-08 02:17:31 +0000654 computeYMD_HMS(&x);
drh7014aff2003-11-01 01:53:53 +0000655 sprintf(zBuf, "%04d-%02d-%02d %02d:%02d:%02d",x.Y, x.M, x.D, x.h, x.m,
656 (int)(x.s));
657 sqlite_set_result_string(context, zBuf, -1);
658 }
659}
660
661/*
662** time( TIMESTRING, MOD, MOD, ...)
663**
664** Return HH:MM:SS
665*/
666static void timeFunc(sqlite_func *context, int argc, const char **argv){
667 DateTime x;
668 if( isDate(argc, argv, &x)==0 ){
669 char zBuf[100];
670 computeHMS(&x);
671 sprintf(zBuf, "%02d:%02d:%02d", x.h, x.m, (int)x.s);
672 sqlite_set_result_string(context, zBuf, -1);
673 }
674}
675
676/*
677** date( TIMESTRING, MOD, MOD, ...)
678**
679** Return YYYY-MM-DD
680*/
681static void dateFunc(sqlite_func *context, int argc, const char **argv){
682 DateTime x;
683 if( isDate(argc, argv, &x)==0 ){
684 char zBuf[100];
685 computeYMD(&x);
686 sprintf(zBuf, "%04d-%02d-%02d", x.Y, x.M, x.D);
687 sqlite_set_result_string(context, zBuf, -1);
688 }
689}
690
691/*
692** strftime( FORMAT, TIMESTRING, MOD, MOD, ...)
693**
694** Return a string described by FORMAT. Conversions as follows:
695**
696** %d day of month
697** %f ** fractional seconds SS.SSS
698** %H hour 00-24
699** %j day of year 000-366
700** %J ** Julian day number
701** %m month 01-12
702** %M minute 00-59
703** %s seconds since 1970-01-01
704** %S seconds 00-59
705** %w day of week 0-6 sunday==0
706** %W week of year 00-53
707** %Y year 0000-9999
708** %% %
709*/
710static void strftimeFunc(sqlite_func *context, int argc, const char **argv){
711 DateTime x;
712 int n, i, j;
713 char *z;
714 const char *zFmt = argv[0];
715 char zBuf[100];
drhf586aa82003-12-23 16:34:12 +0000716 if( argv[0]==0 || isDate(argc-1, argv+1, &x) ) return;
drh7014aff2003-11-01 01:53:53 +0000717 for(i=0, n=1; zFmt[i]; i++, n++){
718 if( zFmt[i]=='%' ){
719 switch( zFmt[i+1] ){
720 case 'd':
721 case 'H':
722 case 'm':
723 case 'M':
724 case 'S':
725 case 'W':
726 n++;
727 /* fall thru */
728 case 'w':
729 case '%':
730 break;
731 case 'f':
732 n += 8;
733 break;
734 case 'j':
735 n += 3;
736 break;
737 case 'Y':
738 n += 8;
739 break;
740 case 's':
741 case 'J':
742 n += 50;
743 break;
744 default:
745 return; /* ERROR. return a NULL */
746 }
747 i++;
748 }
749 }
750 if( n<sizeof(zBuf) ){
751 z = zBuf;
752 }else{
753 z = sqliteMalloc( n );
754 if( z==0 ) return;
755 }
756 computeJD(&x);
drhba212562004-01-08 02:17:31 +0000757 computeYMD_HMS(&x);
drh7014aff2003-11-01 01:53:53 +0000758 for(i=j=0; zFmt[i]; i++){
759 if( zFmt[i]!='%' ){
760 z[j++] = zFmt[i];
761 }else{
762 i++;
763 switch( zFmt[i] ){
764 case 'd': sprintf(&z[j],"%02d",x.D); j+=2; break;
765 case 'f': {
766 int s = x.s;
767 int ms = (x.s - s)*1000.0;
768 sprintf(&z[j],"%02d.%03d",s,ms);
769 j += strlen(&z[j]);
770 break;
771 }
772 case 'H': sprintf(&z[j],"%02d",x.h); j+=2; break;
773 case 'W': /* Fall thru */
774 case 'j': {
775 int n;
776 DateTime y = x;
777 y.validJD = 0;
778 y.M = 1;
779 y.D = 1;
780 computeJD(&y);
781 n = x.rJD - y.rJD + 1;
782 if( zFmt[i]=='W' ){
783 sprintf(&z[j],"%02d",(n+6)/7);
784 j += 2;
785 }else{
786 sprintf(&z[j],"%03d",n);
787 j += 3;
788 }
789 break;
790 }
791 case 'J': sprintf(&z[j],"%.16g",x.rJD); j+=strlen(&z[j]); break;
792 case 'm': sprintf(&z[j],"%02d",x.M); j+=2; break;
793 case 'M': sprintf(&z[j],"%02d",x.m); j+=2; break;
794 case 's': {
drhc5dd9fa2004-01-07 03:29:16 +0000795 sprintf(&z[j],"%d",(int)((x.rJD-2440587.5)*86400.0 + 0.5));
drh7014aff2003-11-01 01:53:53 +0000796 j += strlen(&z[j]);
797 break;
798 }
drhc5dd9fa2004-01-07 03:29:16 +0000799 case 'S': sprintf(&z[j],"%02d",(int)(x.s+0.5)); j+=2; break;
drh7014aff2003-11-01 01:53:53 +0000800 case 'w': z[j++] = (((int)(x.rJD+1.5)) % 7) + '0'; break;
801 case 'Y': sprintf(&z[j],"%04d",x.Y); j+=strlen(&z[j]); break;
802 case '%': z[j++] = '%'; break;
803 }
804 }
805 }
806 z[j] = 0;
807 sqlite_set_result_string(context, z, -1);
808 if( z!=zBuf ){
809 sqliteFree(z);
810 }
811}
812
813
814#endif /* !defined(SQLITE_OMIT_DATETIME_FUNCS) */
815
816/*
817** This function registered all of the above C functions as SQL
818** functions. This should be the only routine in this file with
819** external linkage.
820*/
821void sqliteRegisterDateTimeFunctions(sqlite *db){
822 static struct {
823 char *zName;
824 int nArg;
825 int dataType;
826 void (*xFunc)(sqlite_func*,int,const char**);
827 } aFuncs[] = {
828#ifndef SQLITE_OMIT_DATETIME_FUNCS
829 { "julianday", -1, SQLITE_NUMERIC, juliandayFunc },
830 { "date", -1, SQLITE_TEXT, dateFunc },
drhf586aa82003-12-23 16:34:12 +0000831 { "time", -1, SQLITE_TEXT, timeFunc },
drh7014aff2003-11-01 01:53:53 +0000832 { "datetime", -1, SQLITE_TEXT, datetimeFunc },
833 { "strftime", -1, SQLITE_TEXT, strftimeFunc },
834#endif
835 };
836 int i;
837
838 for(i=0; i<sizeof(aFuncs)/sizeof(aFuncs[0]); i++){
839 sqlite_create_function(db, aFuncs[i].zName,
840 aFuncs[i].nArg, aFuncs[i].xFunc, 0);
841 if( aFuncs[i].xFunc ){
842 sqlite_function_type(db, aFuncs[i].zName, aFuncs[i].dataType);
843 }
844 }
845}