blob: 3e952242ff8c4f6e5b1062de18dcda5dfda989bf [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**
drh4bc05852004-02-10 13:19:35 +000019** $Id: date.c,v 1.10 2004/02/10 13:19:35 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*/
dougcurrieae534182003-12-24 01:41:19 +000050#include "os.h"
51#include "sqliteInt.h"
drh7014aff2003-11-01 01:53:53 +000052#include <ctype.h>
53#include <stdlib.h>
54#include <assert.h>
drh7091cb02003-12-23 16:22:18 +000055#include <time.h>
drh7014aff2003-11-01 01:53:53 +000056
drh4bc05852004-02-10 13:19:35 +000057#ifndef SQLITE_OMIT_DATETIME_FUNCS
58
drh7014aff2003-11-01 01:53:53 +000059/*
60** A structure for holding a single date and time.
61*/
62typedef struct DateTime DateTime;
63struct 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 N digits from zDate into an integer. Return
78** -1 if zDate does not begin with N digits.
79*/
80static int getDigits(const char *zDate, int N){
81 int val = 0;
82 while( N-- ){
83 if( !isdigit(*zDate) ) return -1;
84 val = val*10 + *zDate - '0';
85 zDate++;
86 }
87 return val;
88}
89
90/*
91** Read text from z[] and convert into a floating point number. Return
92** the number of digits converted.
93*/
94static int getValue(const char *z, double *pR){
95 double r = 0.0;
96 double rDivide = 1.0;
97 int isNeg = 0;
98 int nChar = 0;
99 if( *z=='+' ){
100 z++;
101 nChar++;
102 }else if( *z=='-' ){
103 z++;
104 isNeg = 1;
105 nChar++;
106 }
107 if( !isdigit(*z) ) return 0;
108 while( isdigit(*z) ){
109 r = r*10.0 + *z - '0';
110 nChar++;
111 z++;
112 }
113 if( *z=='.' && isdigit(z[1]) ){
114 z++;
115 nChar++;
116 while( isdigit(*z) ){
117 r = r*10.0 + *z - '0';
118 rDivide *= 10.0;
119 nChar++;
120 z++;
121 }
122 r /= rDivide;
123 }
124 if( *z!=0 && !isspace(*z) ) return 0;
125 *pR = isNeg ? -r : r;
126 return nChar;
127}
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*/
141static int parseTimezone(const char *zDate, DateTime *p){
142 int sgn = 0;
143 int nHr, nMn;
144 while( isspace(*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 nHr = getDigits(zDate, 2);
155 if( nHr<0 || nHr>14 ) return 1;
156 zDate += 2;
157 if( zDate[0]!=':' ) return 1;
158 zDate++;
159 nMn = getDigits(zDate, 2);
160 if( nMn<0 || nMn>59 ) return 1;
161 zDate += 2;
162 p->tz = sgn*(nMn + nHr*60);
163 while( isspace(*zDate) ){ zDate++; }
164 return *zDate!=0;
165}
166
167/*
168** Parse times of the form HH:MM or HH:MM:SS or HH:MM:SS.FFFF.
169** The HH, MM, and SS must each be exactly 2 digits. The
170** fractional seconds FFFF can be one or more digits.
171**
172** Return 1 if there is a parsing error and 0 on success.
173*/
174static int parseHhMmSs(const char *zDate, DateTime *p){
175 int h, m, s;
176 double ms = 0.0;
177 h = getDigits(zDate, 2);
178 if( h<0 || zDate[2]!=':' ) return 1;
179 zDate += 3;
180 m = getDigits(zDate, 2);
181 if( m<0 || m>59 ) return 1;
182 zDate += 2;
183 if( *zDate==':' ){
184 s = getDigits(&zDate[1], 2);
185 if( s<0 || s>59 ) return 1;
186 zDate += 3;
187 if( *zDate=='.' && isdigit(zDate[1]) ){
188 double rScale = 1.0;
189 zDate++;
190 while( isdigit(*zDate) ){
191 ms = ms*10.0 + *zDate - '0';
192 rScale *= 10.0;
193 zDate++;
194 }
195 ms /= rScale;
196 }
197 }else{
198 s = 0;
199 }
200 p->validJD = 0;
201 p->validHMS = 1;
202 p->h = h;
203 p->m = m;
204 p->s = s + ms;
205 if( parseTimezone(zDate, p) ) return 1;
206 p->validTZ = p->tz!=0;
207 return 0;
208}
209
210/*
211** Convert from YYYY-MM-DD HH:MM:SS to julian day. We always assume
212** that the YYYY-MM-DD is according to the Gregorian calendar.
213**
214** Reference: Meeus page 61
215*/
216static void computeJD(DateTime *p){
217 int Y, M, D, A, B, X1, X2;
218
219 if( p->validJD ) return;
220 if( p->validYMD ){
221 Y = p->Y;
222 M = p->M;
223 D = p->D;
224 }else{
drhba212562004-01-08 02:17:31 +0000225 Y = 2000; /* If no YMD specified, assume 2000-Jan-01 */
drh7014aff2003-11-01 01:53:53 +0000226 M = 1;
227 D = 1;
228 }
229 if( M<=2 ){
230 Y--;
231 M += 12;
232 }
233 A = Y/100;
234 B = 2 - A + (A/4);
235 X1 = 365.25*(Y+4716);
236 X2 = 30.6001*(M+1);
237 p->rJD = X1 + X2 + D + B - 1524.5;
238 p->validJD = 1;
239 p->validYMD = 0;
240 if( p->validHMS ){
241 p->rJD += (p->h*3600.0 + p->m*60.0 + p->s)/86400.0;
242 if( p->validTZ ){
243 p->rJD += p->tz*60/86400.0;
244 p->validHMS = 0;
245 p->validTZ = 0;
246 }
247 }
248}
249
250/*
251** Parse dates of the form
252**
253** YYYY-MM-DD HH:MM:SS.FFF
254** YYYY-MM-DD HH:MM:SS
255** YYYY-MM-DD HH:MM
256** YYYY-MM-DD
257**
258** Write the result into the DateTime structure and return 0
259** on success and 1 if the input string is not a well-formed
260** date.
261*/
262static int parseYyyyMmDd(const char *zDate, DateTime *p){
263 int Y, M, D;
264
265 Y = getDigits(zDate, 4);
266 if( Y<0 || zDate[4]!='-' ) return 1;
267 zDate += 5;
268 M = getDigits(zDate, 2);
269 if( M<=0 || M>12 || zDate[2]!='-' ) return 1;
270 zDate += 3;
271 D = getDigits(zDate, 2);
272 if( D<=0 || D>31 ) return 1;
273 zDate += 2;
274 while( isspace(*zDate) ){ zDate++; }
275 if( isdigit(*zDate) ){
276 if( parseHhMmSs(zDate, p) ) return 1;
277 }else if( *zDate==0 ){
278 p->validHMS = 0;
279 }else{
280 return 1;
281 }
282 p->validJD = 0;
283 p->validYMD = 1;
284 p->Y = Y;
285 p->M = M;
286 p->D = D;
287 if( p->validTZ ){
288 computeJD(p);
289 }
290 return 0;
291}
292
293/*
294** Attempt to parse the given string into a Julian Day Number. Return
295** the number of errors.
296**
297** The following are acceptable forms for the input string:
298**
299** YYYY-MM-DD HH:MM:SS.FFF +/-HH:MM
300** DDDD.DD
301** now
302**
303** In the first form, the +/-HH:MM is always optional. The fractional
304** seconds extension (the ".FFF") is optional. The seconds portion
305** (":SS.FFF") is option. The year and date can be omitted as long
306** as there is a time string. The time string can be omitted as long
307** as there is a year and date.
308*/
309static int parseDateOrTime(const char *zDate, DateTime *p){
310 int i;
311 memset(p, 0, sizeof(*p));
312 for(i=0; isdigit(zDate[i]); i++){}
313 if( i==4 && zDate[i]=='-' ){
314 return parseYyyyMmDd(zDate, p);
315 }else if( i==2 && zDate[i]==':' ){
316 return parseHhMmSs(zDate, p);
317 return 0;
318 }else if( i==0 && sqliteStrICmp(zDate,"now")==0 ){
319 double r;
320 if( sqliteOsCurrentTime(&r)==0 ){
321 p->rJD = r;
322 p->validJD = 1;
323 return 0;
324 }
325 return 1;
326 }else if( sqliteIsNumber(zDate) ){
drh93a5c6b2003-12-23 02:17:35 +0000327 p->rJD = sqliteAtoF(zDate);
drh7014aff2003-11-01 01:53:53 +0000328 p->validJD = 1;
329 return 0;
330 }
331 return 1;
332}
333
334/*
335** Compute the Year, Month, and Day from the julian day number.
336*/
337static void computeYMD(DateTime *p){
338 int Z, A, B, C, D, E, X1;
339 if( p->validYMD ) return;
340 Z = p->rJD + 0.5;
341 A = (Z - 1867216.25)/36524.25;
342 A = Z + 1 + A - (A/4);
343 B = A + 1524;
344 C = (B - 122.1)/365.25;
345 D = 365.25*C;
346 E = (B-D)/30.6001;
347 X1 = 30.6001*E;
348 p->D = B - D - X1;
349 p->M = E<14 ? E-1 : E-13;
350 p->Y = p->M>2 ? C - 4716 : C - 4715;
351 p->validYMD = 1;
352}
353
354/*
355** Compute the Hour, Minute, and Seconds from the julian day number.
356*/
357static void computeHMS(DateTime *p){
358 int Z, s;
359 if( p->validHMS ) return;
360 Z = p->rJD + 0.5;
361 s = (p->rJD + 0.5 - Z)*86400000.0 + 0.5;
362 p->s = 0.001*s;
363 s = p->s;
364 p->s -= s;
365 p->h = s/3600;
366 s -= p->h*3600;
367 p->m = s/60;
368 p->s += s - p->m*60;
369 p->validHMS = 1;
370}
371
372/*
drhba212562004-01-08 02:17:31 +0000373** Compute both YMD and HMS
374*/
375static void computeYMD_HMS(DateTime *p){
376 computeYMD(p);
377 computeHMS(p);
378}
379
380/*
381** Clear the YMD and HMS and the TZ
382*/
383static void clearYMD_HMS_TZ(DateTime *p){
384 p->validYMD = 0;
385 p->validHMS = 0;
386 p->validTZ = 0;
387}
388
389/*
drh7091cb02003-12-23 16:22:18 +0000390** Compute the difference (in days) between localtime and UTC (a.k.a. GMT)
391** for the time value p where p is in UTC.
392*/
393static double localtimeOffset(DateTime *p){
394 DateTime x, y;
395 time_t t;
396 struct tm *pTm;
drh7091cb02003-12-23 16:22:18 +0000397 x = *p;
drhba212562004-01-08 02:17:31 +0000398 computeYMD_HMS(&x);
drh7091cb02003-12-23 16:22:18 +0000399 if( x.Y<1971 || x.Y>=2038 ){
400 x.Y = 2000;
401 x.M = 1;
402 x.D = 1;
403 x.h = 0;
404 x.m = 0;
405 x.s = 0.0;
406 } else {
407 int s = x.s + 0.5;
408 x.s = s;
409 }
410 x.tz = 0;
411 x.validJD = 0;
412 computeJD(&x);
413 t = (x.rJD-2440587.5)*86400.0 + 0.5;
414 sqliteOsEnterMutex();
415 pTm = localtime(&t);
416 y.Y = pTm->tm_year + 1900;
417 y.M = pTm->tm_mon + 1;
418 y.D = pTm->tm_mday;
419 y.h = pTm->tm_hour;
420 y.m = pTm->tm_min;
421 y.s = pTm->tm_sec;
422 sqliteOsLeaveMutex();
423 y.validYMD = 1;
424 y.validHMS = 1;
425 y.validJD = 0;
426 y.validTZ = 0;
427 computeJD(&y);
drh7091cb02003-12-23 16:22:18 +0000428 return y.rJD - x.rJD;
429}
430
431/*
drh7014aff2003-11-01 01:53:53 +0000432** Process a modifier to a date-time stamp. The modifiers are
433** as follows:
434**
435** NNN days
436** NNN hours
437** NNN minutes
438** NNN.NNNN seconds
439** NNN months
440** NNN years
441** start of month
442** start of year
443** start of week
444** start of day
445** weekday N
446** unixepoch
drh7091cb02003-12-23 16:22:18 +0000447** localtime
448** utc
drh7014aff2003-11-01 01:53:53 +0000449**
450** Return 0 on success and 1 if there is any kind of error.
451*/
452static int parseModifier(const char *zMod, DateTime *p){
453 int rc = 1;
454 int n;
455 double r;
drh4d5b8362004-01-17 01:16:21 +0000456 char *z, zBuf[30];
457 z = zBuf;
458 for(n=0; n<sizeof(zBuf)-1 && zMod[n]; n++){
drh7014aff2003-11-01 01:53:53 +0000459 z[n] = tolower(zMod[n]);
460 }
461 z[n] = 0;
462 switch( z[0] ){
drh7091cb02003-12-23 16:22:18 +0000463 case 'l': {
464 /* localtime
465 **
466 ** Assuming the current time value is UTC (a.k.a. GMT), shift it to
467 ** show local time.
468 */
469 if( strcmp(z, "localtime")==0 ){
470 computeJD(p);
471 p->rJD += localtimeOffset(p);
drhba212562004-01-08 02:17:31 +0000472 clearYMD_HMS_TZ(p);
drh7091cb02003-12-23 16:22:18 +0000473 rc = 0;
474 }
475 break;
476 }
drh7014aff2003-11-01 01:53:53 +0000477 case 'u': {
478 /*
479 ** unixepoch
480 **
481 ** Treat the current value of p->rJD as the number of
482 ** seconds since 1970. Convert to a real julian day number.
483 */
484 if( strcmp(z, "unixepoch")==0 && p->validJD ){
485 p->rJD = p->rJD/86400.0 + 2440587.5;
drhba212562004-01-08 02:17:31 +0000486 clearYMD_HMS_TZ(p);
drh7014aff2003-11-01 01:53:53 +0000487 rc = 0;
drh7091cb02003-12-23 16:22:18 +0000488 }else if( strcmp(z, "utc")==0 ){
489 double c1;
490 computeJD(p);
491 c1 = localtimeOffset(p);
492 p->rJD -= c1;
drhba212562004-01-08 02:17:31 +0000493 clearYMD_HMS_TZ(p);
drh7091cb02003-12-23 16:22:18 +0000494 p->rJD += c1 - localtimeOffset(p);
drh7091cb02003-12-23 16:22:18 +0000495 rc = 0;
drh7014aff2003-11-01 01:53:53 +0000496 }
497 break;
498 }
499 case 'w': {
500 /*
501 ** weekday N
502 **
drhc5dd9fa2004-01-07 03:29:16 +0000503 ** Move the date to the same time on the next occurrance of
drh7014aff2003-11-01 01:53:53 +0000504 ** weekday N where 0==Sunday, 1==Monday, and so forth. If the
drhc5dd9fa2004-01-07 03:29:16 +0000505 ** date is already on the appropriate weekday, this is a no-op.
drh7014aff2003-11-01 01:53:53 +0000506 */
507 if( strncmp(z, "weekday ", 8)==0 && getValue(&z[8],&r)>0
508 && (n=r)==r && n>=0 && r<7 ){
509 int Z;
drhba212562004-01-08 02:17:31 +0000510 computeYMD_HMS(p);
drh7014aff2003-11-01 01:53:53 +0000511 p->validTZ = 0;
512 p->validJD = 0;
513 computeJD(p);
514 Z = p->rJD + 1.5;
515 Z %= 7;
516 if( Z>n ) Z -= 7;
517 p->rJD += n - Z;
drhba212562004-01-08 02:17:31 +0000518 clearYMD_HMS_TZ(p);
drh7014aff2003-11-01 01:53:53 +0000519 rc = 0;
520 }
521 break;
522 }
523 case 's': {
524 /*
525 ** start of TTTTT
526 **
527 ** Move the date backwards to the beginning of the current day,
528 ** or month or year.
529 */
530 if( strncmp(z, "start of ", 9)!=0 ) break;
drh4d5b8362004-01-17 01:16:21 +0000531 z += 9;
drh7014aff2003-11-01 01:53:53 +0000532 computeYMD(p);
533 p->validHMS = 1;
534 p->h = p->m = 0;
535 p->s = 0.0;
536 p->validTZ = 0;
537 p->validJD = 0;
drh4d5b8362004-01-17 01:16:21 +0000538 if( strcmp(z,"month")==0 ){
drh7014aff2003-11-01 01:53:53 +0000539 p->D = 1;
540 rc = 0;
drh4d5b8362004-01-17 01:16:21 +0000541 }else if( strcmp(z,"year")==0 ){
drh7014aff2003-11-01 01:53:53 +0000542 computeYMD(p);
543 p->M = 1;
544 p->D = 1;
545 rc = 0;
drh4d5b8362004-01-17 01:16:21 +0000546 }else if( strcmp(z,"day")==0 ){
drh7014aff2003-11-01 01:53:53 +0000547 rc = 0;
548 }
549 break;
550 }
551 case '+':
552 case '-':
553 case '0':
554 case '1':
555 case '2':
556 case '3':
557 case '4':
558 case '5':
559 case '6':
560 case '7':
561 case '8':
562 case '9': {
563 n = getValue(z, &r);
564 if( n<=0 ) break;
drh4d5b8362004-01-17 01:16:21 +0000565 z += n;
566 while( isspace(z[0]) ) z++;
567 n = strlen(z);
drh7014aff2003-11-01 01:53:53 +0000568 if( n>10 || n<3 ) break;
drh7014aff2003-11-01 01:53:53 +0000569 if( z[n-1]=='s' ){ z[n-1] = 0; n--; }
570 computeJD(p);
571 rc = 0;
572 if( n==3 && strcmp(z,"day")==0 ){
573 p->rJD += r;
574 }else if( n==4 && strcmp(z,"hour")==0 ){
drh7014aff2003-11-01 01:53:53 +0000575 p->rJD += r/24.0;
576 }else if( n==6 && strcmp(z,"minute")==0 ){
drh7014aff2003-11-01 01:53:53 +0000577 p->rJD += r/(24.0*60.0);
578 }else if( n==6 && strcmp(z,"second")==0 ){
drh7014aff2003-11-01 01:53:53 +0000579 p->rJD += r/(24.0*60.0*60.0);
580 }else if( n==5 && strcmp(z,"month")==0 ){
581 int x, y;
drhba212562004-01-08 02:17:31 +0000582 computeYMD_HMS(p);
drh7014aff2003-11-01 01:53:53 +0000583 p->M += r;
584 x = p->M>0 ? (p->M-1)/12 : (p->M-12)/12;
585 p->Y += x;
586 p->M -= x*12;
587 p->validJD = 0;
588 computeJD(p);
589 y = r;
590 if( y!=r ){
591 p->rJD += (r - y)*30.0;
592 }
593 }else if( n==4 && strcmp(z,"year")==0 ){
drhba212562004-01-08 02:17:31 +0000594 computeYMD_HMS(p);
drh7014aff2003-11-01 01:53:53 +0000595 p->Y += r;
596 p->validJD = 0;
597 computeJD(p);
598 }else{
599 rc = 1;
600 }
drhba212562004-01-08 02:17:31 +0000601 clearYMD_HMS_TZ(p);
drh7014aff2003-11-01 01:53:53 +0000602 break;
603 }
604 default: {
605 break;
606 }
607 }
608 return rc;
609}
610
611/*
612** Process time function arguments. argv[0] is a date-time stamp.
613** argv[1] and following are modifiers. Parse them all and write
614** the resulting time into the DateTime structure p. Return 0
615** on success and 1 if there are any errors.
616*/
617static int isDate(int argc, const char **argv, DateTime *p){
618 int i;
619 if( argc==0 ) return 1;
drhf586aa82003-12-23 16:34:12 +0000620 if( argv[0]==0 || parseDateOrTime(argv[0], p) ) return 1;
drh7014aff2003-11-01 01:53:53 +0000621 for(i=1; i<argc; i++){
drhf586aa82003-12-23 16:34:12 +0000622 if( argv[i]==0 || parseModifier(argv[i], p) ) return 1;
drh7014aff2003-11-01 01:53:53 +0000623 }
624 return 0;
625}
626
627
628/*
629** The following routines implement the various date and time functions
630** of SQLite.
631*/
632
633/*
634** julianday( TIMESTRING, MOD, MOD, ...)
635**
636** Return the julian day number of the date specified in the arguments
637*/
638static void juliandayFunc(sqlite_func *context, int argc, const char **argv){
639 DateTime x;
640 if( isDate(argc, argv, &x)==0 ){
641 computeJD(&x);
642 sqlite_set_result_double(context, x.rJD);
643 }
644}
645
646/*
647** datetime( TIMESTRING, MOD, MOD, ...)
648**
649** Return YYYY-MM-DD HH:MM:SS
650*/
651static void datetimeFunc(sqlite_func *context, int argc, const char **argv){
652 DateTime x;
653 if( isDate(argc, argv, &x)==0 ){
654 char zBuf[100];
drhba212562004-01-08 02:17:31 +0000655 computeYMD_HMS(&x);
drh7014aff2003-11-01 01:53:53 +0000656 sprintf(zBuf, "%04d-%02d-%02d %02d:%02d:%02d",x.Y, x.M, x.D, x.h, x.m,
657 (int)(x.s));
658 sqlite_set_result_string(context, zBuf, -1);
659 }
660}
661
662/*
663** time( TIMESTRING, MOD, MOD, ...)
664**
665** Return HH:MM:SS
666*/
667static void timeFunc(sqlite_func *context, int argc, const char **argv){
668 DateTime x;
669 if( isDate(argc, argv, &x)==0 ){
670 char zBuf[100];
671 computeHMS(&x);
672 sprintf(zBuf, "%02d:%02d:%02d", x.h, x.m, (int)x.s);
673 sqlite_set_result_string(context, zBuf, -1);
674 }
675}
676
677/*
678** date( TIMESTRING, MOD, MOD, ...)
679**
680** Return YYYY-MM-DD
681*/
682static void dateFunc(sqlite_func *context, int argc, const char **argv){
683 DateTime x;
684 if( isDate(argc, argv, &x)==0 ){
685 char zBuf[100];
686 computeYMD(&x);
687 sprintf(zBuf, "%04d-%02d-%02d", x.Y, x.M, x.D);
688 sqlite_set_result_string(context, zBuf, -1);
689 }
690}
691
692/*
693** strftime( FORMAT, TIMESTRING, MOD, MOD, ...)
694**
695** Return a string described by FORMAT. Conversions as follows:
696**
697** %d day of month
698** %f ** fractional seconds SS.SSS
699** %H hour 00-24
700** %j day of year 000-366
701** %J ** Julian day number
702** %m month 01-12
703** %M minute 00-59
704** %s seconds since 1970-01-01
705** %S seconds 00-59
706** %w day of week 0-6 sunday==0
707** %W week of year 00-53
708** %Y year 0000-9999
709** %% %
710*/
711static void strftimeFunc(sqlite_func *context, int argc, const char **argv){
712 DateTime x;
713 int n, i, j;
714 char *z;
715 const char *zFmt = argv[0];
716 char zBuf[100];
drhf586aa82003-12-23 16:34:12 +0000717 if( argv[0]==0 || isDate(argc-1, argv+1, &x) ) return;
drh7014aff2003-11-01 01:53:53 +0000718 for(i=0, n=1; zFmt[i]; i++, n++){
719 if( zFmt[i]=='%' ){
720 switch( zFmt[i+1] ){
721 case 'd':
722 case 'H':
723 case 'm':
724 case 'M':
725 case 'S':
726 case 'W':
727 n++;
728 /* fall thru */
729 case 'w':
730 case '%':
731 break;
732 case 'f':
733 n += 8;
734 break;
735 case 'j':
736 n += 3;
737 break;
738 case 'Y':
739 n += 8;
740 break;
741 case 's':
742 case 'J':
743 n += 50;
744 break;
745 default:
746 return; /* ERROR. return a NULL */
747 }
748 i++;
749 }
750 }
751 if( n<sizeof(zBuf) ){
752 z = zBuf;
753 }else{
754 z = sqliteMalloc( n );
755 if( z==0 ) return;
756 }
757 computeJD(&x);
drhba212562004-01-08 02:17:31 +0000758 computeYMD_HMS(&x);
drh7014aff2003-11-01 01:53:53 +0000759 for(i=j=0; zFmt[i]; i++){
760 if( zFmt[i]!='%' ){
761 z[j++] = zFmt[i];
762 }else{
763 i++;
764 switch( zFmt[i] ){
765 case 'd': sprintf(&z[j],"%02d",x.D); j+=2; break;
766 case 'f': {
767 int s = x.s;
768 int ms = (x.s - s)*1000.0;
769 sprintf(&z[j],"%02d.%03d",s,ms);
770 j += strlen(&z[j]);
771 break;
772 }
773 case 'H': sprintf(&z[j],"%02d",x.h); j+=2; break;
774 case 'W': /* Fall thru */
775 case 'j': {
776 int n;
777 DateTime y = x;
778 y.validJD = 0;
779 y.M = 1;
780 y.D = 1;
781 computeJD(&y);
782 n = x.rJD - y.rJD + 1;
783 if( zFmt[i]=='W' ){
784 sprintf(&z[j],"%02d",(n+6)/7);
785 j += 2;
786 }else{
787 sprintf(&z[j],"%03d",n);
788 j += 3;
789 }
790 break;
791 }
792 case 'J': sprintf(&z[j],"%.16g",x.rJD); j+=strlen(&z[j]); break;
793 case 'm': sprintf(&z[j],"%02d",x.M); j+=2; break;
794 case 'M': sprintf(&z[j],"%02d",x.m); j+=2; break;
795 case 's': {
drhc5dd9fa2004-01-07 03:29:16 +0000796 sprintf(&z[j],"%d",(int)((x.rJD-2440587.5)*86400.0 + 0.5));
drh7014aff2003-11-01 01:53:53 +0000797 j += strlen(&z[j]);
798 break;
799 }
drhc5dd9fa2004-01-07 03:29:16 +0000800 case 'S': sprintf(&z[j],"%02d",(int)(x.s+0.5)); j+=2; break;
drh7014aff2003-11-01 01:53:53 +0000801 case 'w': z[j++] = (((int)(x.rJD+1.5)) % 7) + '0'; break;
802 case 'Y': sprintf(&z[j],"%04d",x.Y); j+=strlen(&z[j]); break;
803 case '%': z[j++] = '%'; break;
804 }
805 }
806 }
807 z[j] = 0;
808 sqlite_set_result_string(context, z, -1);
809 if( z!=zBuf ){
810 sqliteFree(z);
811 }
812}
813
814
815#endif /* !defined(SQLITE_OMIT_DATETIME_FUNCS) */
816
817/*
818** This function registered all of the above C functions as SQL
819** functions. This should be the only routine in this file with
820** external linkage.
821*/
822void sqliteRegisterDateTimeFunctions(sqlite *db){
823 static struct {
824 char *zName;
825 int nArg;
826 int dataType;
827 void (*xFunc)(sqlite_func*,int,const char**);
828 } aFuncs[] = {
829#ifndef SQLITE_OMIT_DATETIME_FUNCS
830 { "julianday", -1, SQLITE_NUMERIC, juliandayFunc },
831 { "date", -1, SQLITE_TEXT, dateFunc },
drhf586aa82003-12-23 16:34:12 +0000832 { "time", -1, SQLITE_TEXT, timeFunc },
drh7014aff2003-11-01 01:53:53 +0000833 { "datetime", -1, SQLITE_TEXT, datetimeFunc },
834 { "strftime", -1, SQLITE_TEXT, strftimeFunc },
835#endif
836 };
837 int i;
838
839 for(i=0; i<sizeof(aFuncs)/sizeof(aFuncs[0]); i++){
840 sqlite_create_function(db, aFuncs[i].zName,
841 aFuncs[i].nArg, aFuncs[i].xFunc, 0);
842 if( aFuncs[i].xFunc ){
843 sqlite_function_type(db, aFuncs[i].zName, aFuncs[i].dataType);
844 }
845 }
846}