blob: 3a4addc9e6eea483c95ac57de749996eeee54397 [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**
drh8eb2cce2004-02-21 03:28:18 +000019** $Id: date.c,v 1.11 2004/02/21 03:28:18 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){
drh8eb2cce2004-02-21 03:28:18 +0000263 int Y, M, D, neg;
drh7014aff2003-11-01 01:53:53 +0000264
drh8eb2cce2004-02-21 03:28:18 +0000265 if( zDate[0]=='-' ){
266 zDate++;
267 neg = 1;
268 }else{
269 neg = 0;
270 }
drh7014aff2003-11-01 01:53:53 +0000271 Y = getDigits(zDate, 4);
272 if( Y<0 || zDate[4]!='-' ) return 1;
273 zDate += 5;
274 M = getDigits(zDate, 2);
275 if( M<=0 || M>12 || zDate[2]!='-' ) return 1;
276 zDate += 3;
277 D = getDigits(zDate, 2);
278 if( D<=0 || D>31 ) return 1;
279 zDate += 2;
280 while( isspace(*zDate) ){ zDate++; }
281 if( isdigit(*zDate) ){
282 if( parseHhMmSs(zDate, p) ) return 1;
283 }else if( *zDate==0 ){
284 p->validHMS = 0;
285 }else{
286 return 1;
287 }
288 p->validJD = 0;
289 p->validYMD = 1;
drh8eb2cce2004-02-21 03:28:18 +0000290 p->Y = neg ? -Y : Y;
drh7014aff2003-11-01 01:53:53 +0000291 p->M = M;
292 p->D = D;
293 if( p->validTZ ){
294 computeJD(p);
295 }
296 return 0;
297}
298
299/*
300** Attempt to parse the given string into a Julian Day Number. Return
301** the number of errors.
302**
303** The following are acceptable forms for the input string:
304**
305** YYYY-MM-DD HH:MM:SS.FFF +/-HH:MM
306** DDDD.DD
307** now
308**
309** In the first form, the +/-HH:MM is always optional. The fractional
310** seconds extension (the ".FFF") is optional. The seconds portion
311** (":SS.FFF") is option. The year and date can be omitted as long
312** as there is a time string. The time string can be omitted as long
313** as there is a year and date.
314*/
315static int parseDateOrTime(const char *zDate, DateTime *p){
drh7014aff2003-11-01 01:53:53 +0000316 memset(p, 0, sizeof(*p));
drh8eb2cce2004-02-21 03:28:18 +0000317 if( parseYyyyMmDd(zDate,p)==0 ){
drh7014aff2003-11-01 01:53:53 +0000318 return 0;
drh8eb2cce2004-02-21 03:28:18 +0000319 }else if( parseHhMmSs(zDate, p)==0 ){
320 return 0;
321 }else if( sqliteStrICmp(zDate,"now")==0){
drh7014aff2003-11-01 01:53:53 +0000322 double r;
323 if( sqliteOsCurrentTime(&r)==0 ){
324 p->rJD = r;
325 p->validJD = 1;
326 return 0;
327 }
328 return 1;
329 }else if( sqliteIsNumber(zDate) ){
drh93a5c6b2003-12-23 02:17:35 +0000330 p->rJD = sqliteAtoF(zDate);
drh7014aff2003-11-01 01:53:53 +0000331 p->validJD = 1;
332 return 0;
333 }
334 return 1;
335}
336
337/*
338** Compute the Year, Month, and Day from the julian day number.
339*/
340static void computeYMD(DateTime *p){
341 int Z, A, B, C, D, E, X1;
342 if( p->validYMD ) return;
343 Z = p->rJD + 0.5;
344 A = (Z - 1867216.25)/36524.25;
345 A = Z + 1 + A - (A/4);
346 B = A + 1524;
347 C = (B - 122.1)/365.25;
348 D = 365.25*C;
349 E = (B-D)/30.6001;
350 X1 = 30.6001*E;
351 p->D = B - D - X1;
352 p->M = E<14 ? E-1 : E-13;
353 p->Y = p->M>2 ? C - 4716 : C - 4715;
354 p->validYMD = 1;
355}
356
357/*
358** Compute the Hour, Minute, and Seconds from the julian day number.
359*/
360static void computeHMS(DateTime *p){
361 int Z, s;
362 if( p->validHMS ) return;
363 Z = p->rJD + 0.5;
364 s = (p->rJD + 0.5 - Z)*86400000.0 + 0.5;
365 p->s = 0.001*s;
366 s = p->s;
367 p->s -= s;
368 p->h = s/3600;
369 s -= p->h*3600;
370 p->m = s/60;
371 p->s += s - p->m*60;
372 p->validHMS = 1;
373}
374
375/*
drhba212562004-01-08 02:17:31 +0000376** Compute both YMD and HMS
377*/
378static void computeYMD_HMS(DateTime *p){
379 computeYMD(p);
380 computeHMS(p);
381}
382
383/*
384** Clear the YMD and HMS and the TZ
385*/
386static void clearYMD_HMS_TZ(DateTime *p){
387 p->validYMD = 0;
388 p->validHMS = 0;
389 p->validTZ = 0;
390}
391
392/*
drh7091cb02003-12-23 16:22:18 +0000393** Compute the difference (in days) between localtime and UTC (a.k.a. GMT)
394** for the time value p where p is in UTC.
395*/
396static double localtimeOffset(DateTime *p){
397 DateTime x, y;
398 time_t t;
399 struct tm *pTm;
drh7091cb02003-12-23 16:22:18 +0000400 x = *p;
drhba212562004-01-08 02:17:31 +0000401 computeYMD_HMS(&x);
drh7091cb02003-12-23 16:22:18 +0000402 if( x.Y<1971 || x.Y>=2038 ){
403 x.Y = 2000;
404 x.M = 1;
405 x.D = 1;
406 x.h = 0;
407 x.m = 0;
408 x.s = 0.0;
409 } else {
410 int s = x.s + 0.5;
411 x.s = s;
412 }
413 x.tz = 0;
414 x.validJD = 0;
415 computeJD(&x);
416 t = (x.rJD-2440587.5)*86400.0 + 0.5;
417 sqliteOsEnterMutex();
418 pTm = localtime(&t);
419 y.Y = pTm->tm_year + 1900;
420 y.M = pTm->tm_mon + 1;
421 y.D = pTm->tm_mday;
422 y.h = pTm->tm_hour;
423 y.m = pTm->tm_min;
424 y.s = pTm->tm_sec;
425 sqliteOsLeaveMutex();
426 y.validYMD = 1;
427 y.validHMS = 1;
428 y.validJD = 0;
429 y.validTZ = 0;
430 computeJD(&y);
drh7091cb02003-12-23 16:22:18 +0000431 return y.rJD - x.rJD;
432}
433
434/*
drh7014aff2003-11-01 01:53:53 +0000435** Process a modifier to a date-time stamp. The modifiers are
436** as follows:
437**
438** NNN days
439** NNN hours
440** NNN minutes
441** NNN.NNNN seconds
442** NNN months
443** NNN years
444** start of month
445** start of year
446** start of week
447** start of day
448** weekday N
449** unixepoch
drh7091cb02003-12-23 16:22:18 +0000450** localtime
451** utc
drh7014aff2003-11-01 01:53:53 +0000452**
453** Return 0 on success and 1 if there is any kind of error.
454*/
455static int parseModifier(const char *zMod, DateTime *p){
456 int rc = 1;
457 int n;
458 double r;
drh4d5b8362004-01-17 01:16:21 +0000459 char *z, zBuf[30];
460 z = zBuf;
461 for(n=0; n<sizeof(zBuf)-1 && zMod[n]; n++){
drh7014aff2003-11-01 01:53:53 +0000462 z[n] = tolower(zMod[n]);
463 }
464 z[n] = 0;
465 switch( z[0] ){
drh7091cb02003-12-23 16:22:18 +0000466 case 'l': {
467 /* localtime
468 **
469 ** Assuming the current time value is UTC (a.k.a. GMT), shift it to
470 ** show local time.
471 */
472 if( strcmp(z, "localtime")==0 ){
473 computeJD(p);
474 p->rJD += localtimeOffset(p);
drhba212562004-01-08 02:17:31 +0000475 clearYMD_HMS_TZ(p);
drh7091cb02003-12-23 16:22:18 +0000476 rc = 0;
477 }
478 break;
479 }
drh7014aff2003-11-01 01:53:53 +0000480 case 'u': {
481 /*
482 ** unixepoch
483 **
484 ** Treat the current value of p->rJD as the number of
485 ** seconds since 1970. Convert to a real julian day number.
486 */
487 if( strcmp(z, "unixepoch")==0 && p->validJD ){
488 p->rJD = p->rJD/86400.0 + 2440587.5;
drhba212562004-01-08 02:17:31 +0000489 clearYMD_HMS_TZ(p);
drh7014aff2003-11-01 01:53:53 +0000490 rc = 0;
drh7091cb02003-12-23 16:22:18 +0000491 }else if( strcmp(z, "utc")==0 ){
492 double c1;
493 computeJD(p);
494 c1 = localtimeOffset(p);
495 p->rJD -= c1;
drhba212562004-01-08 02:17:31 +0000496 clearYMD_HMS_TZ(p);
drh7091cb02003-12-23 16:22:18 +0000497 p->rJD += c1 - localtimeOffset(p);
drh7091cb02003-12-23 16:22:18 +0000498 rc = 0;
drh7014aff2003-11-01 01:53:53 +0000499 }
500 break;
501 }
502 case 'w': {
503 /*
504 ** weekday N
505 **
drhc5dd9fa2004-01-07 03:29:16 +0000506 ** Move the date to the same time on the next occurrance of
drh7014aff2003-11-01 01:53:53 +0000507 ** weekday N where 0==Sunday, 1==Monday, and so forth. If the
drhc5dd9fa2004-01-07 03:29:16 +0000508 ** date is already on the appropriate weekday, this is a no-op.
drh7014aff2003-11-01 01:53:53 +0000509 */
510 if( strncmp(z, "weekday ", 8)==0 && getValue(&z[8],&r)>0
511 && (n=r)==r && n>=0 && r<7 ){
512 int Z;
drhba212562004-01-08 02:17:31 +0000513 computeYMD_HMS(p);
drh7014aff2003-11-01 01:53:53 +0000514 p->validTZ = 0;
515 p->validJD = 0;
516 computeJD(p);
517 Z = p->rJD + 1.5;
518 Z %= 7;
519 if( Z>n ) Z -= 7;
520 p->rJD += n - Z;
drhba212562004-01-08 02:17:31 +0000521 clearYMD_HMS_TZ(p);
drh7014aff2003-11-01 01:53:53 +0000522 rc = 0;
523 }
524 break;
525 }
526 case 's': {
527 /*
528 ** start of TTTTT
529 **
530 ** Move the date backwards to the beginning of the current day,
531 ** or month or year.
532 */
533 if( strncmp(z, "start of ", 9)!=0 ) break;
drh4d5b8362004-01-17 01:16:21 +0000534 z += 9;
drh7014aff2003-11-01 01:53:53 +0000535 computeYMD(p);
536 p->validHMS = 1;
537 p->h = p->m = 0;
538 p->s = 0.0;
539 p->validTZ = 0;
540 p->validJD = 0;
drh4d5b8362004-01-17 01:16:21 +0000541 if( strcmp(z,"month")==0 ){
drh7014aff2003-11-01 01:53:53 +0000542 p->D = 1;
543 rc = 0;
drh4d5b8362004-01-17 01:16:21 +0000544 }else if( strcmp(z,"year")==0 ){
drh7014aff2003-11-01 01:53:53 +0000545 computeYMD(p);
546 p->M = 1;
547 p->D = 1;
548 rc = 0;
drh4d5b8362004-01-17 01:16:21 +0000549 }else if( strcmp(z,"day")==0 ){
drh7014aff2003-11-01 01:53:53 +0000550 rc = 0;
551 }
552 break;
553 }
554 case '+':
555 case '-':
556 case '0':
557 case '1':
558 case '2':
559 case '3':
560 case '4':
561 case '5':
562 case '6':
563 case '7':
564 case '8':
565 case '9': {
566 n = getValue(z, &r);
567 if( n<=0 ) break;
drh4d5b8362004-01-17 01:16:21 +0000568 z += n;
569 while( isspace(z[0]) ) z++;
570 n = strlen(z);
drh7014aff2003-11-01 01:53:53 +0000571 if( n>10 || n<3 ) break;
drh7014aff2003-11-01 01:53:53 +0000572 if( z[n-1]=='s' ){ z[n-1] = 0; n--; }
573 computeJD(p);
574 rc = 0;
575 if( n==3 && strcmp(z,"day")==0 ){
576 p->rJD += r;
577 }else if( n==4 && strcmp(z,"hour")==0 ){
drh7014aff2003-11-01 01:53:53 +0000578 p->rJD += r/24.0;
579 }else if( n==6 && strcmp(z,"minute")==0 ){
drh7014aff2003-11-01 01:53:53 +0000580 p->rJD += r/(24.0*60.0);
581 }else if( n==6 && strcmp(z,"second")==0 ){
drh7014aff2003-11-01 01:53:53 +0000582 p->rJD += r/(24.0*60.0*60.0);
583 }else if( n==5 && strcmp(z,"month")==0 ){
584 int x, y;
drhba212562004-01-08 02:17:31 +0000585 computeYMD_HMS(p);
drh7014aff2003-11-01 01:53:53 +0000586 p->M += r;
587 x = p->M>0 ? (p->M-1)/12 : (p->M-12)/12;
588 p->Y += x;
589 p->M -= x*12;
590 p->validJD = 0;
591 computeJD(p);
592 y = r;
593 if( y!=r ){
594 p->rJD += (r - y)*30.0;
595 }
596 }else if( n==4 && strcmp(z,"year")==0 ){
drhba212562004-01-08 02:17:31 +0000597 computeYMD_HMS(p);
drh7014aff2003-11-01 01:53:53 +0000598 p->Y += r;
599 p->validJD = 0;
600 computeJD(p);
601 }else{
602 rc = 1;
603 }
drhba212562004-01-08 02:17:31 +0000604 clearYMD_HMS_TZ(p);
drh7014aff2003-11-01 01:53:53 +0000605 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];
drhba212562004-01-08 02:17:31 +0000658 computeYMD_HMS(&x);
drh7014aff2003-11-01 01:53:53 +0000659 sprintf(zBuf, "%04d-%02d-%02d %02d:%02d:%02d",x.Y, x.M, x.D, x.h, x.m,
660 (int)(x.s));
661 sqlite_set_result_string(context, zBuf, -1);
662 }
663}
664
665/*
666** time( TIMESTRING, MOD, MOD, ...)
667**
668** Return HH:MM:SS
669*/
670static void timeFunc(sqlite_func *context, int argc, const char **argv){
671 DateTime x;
672 if( isDate(argc, argv, &x)==0 ){
673 char zBuf[100];
674 computeHMS(&x);
675 sprintf(zBuf, "%02d:%02d:%02d", x.h, x.m, (int)x.s);
676 sqlite_set_result_string(context, zBuf, -1);
677 }
678}
679
680/*
681** date( TIMESTRING, MOD, MOD, ...)
682**
683** Return YYYY-MM-DD
684*/
685static void dateFunc(sqlite_func *context, int argc, const char **argv){
686 DateTime x;
687 if( isDate(argc, argv, &x)==0 ){
688 char zBuf[100];
689 computeYMD(&x);
690 sprintf(zBuf, "%04d-%02d-%02d", x.Y, x.M, x.D);
691 sqlite_set_result_string(context, zBuf, -1);
692 }
693}
694
695/*
696** strftime( FORMAT, TIMESTRING, MOD, MOD, ...)
697**
698** Return a string described by FORMAT. Conversions as follows:
699**
700** %d day of month
701** %f ** fractional seconds SS.SSS
702** %H hour 00-24
703** %j day of year 000-366
704** %J ** Julian day number
705** %m month 01-12
706** %M minute 00-59
707** %s seconds since 1970-01-01
708** %S seconds 00-59
709** %w day of week 0-6 sunday==0
710** %W week of year 00-53
711** %Y year 0000-9999
712** %% %
713*/
714static void strftimeFunc(sqlite_func *context, int argc, const char **argv){
715 DateTime x;
716 int n, i, j;
717 char *z;
718 const char *zFmt = argv[0];
719 char zBuf[100];
drhf586aa82003-12-23 16:34:12 +0000720 if( argv[0]==0 || isDate(argc-1, argv+1, &x) ) return;
drh7014aff2003-11-01 01:53:53 +0000721 for(i=0, n=1; zFmt[i]; i++, n++){
722 if( zFmt[i]=='%' ){
723 switch( zFmt[i+1] ){
724 case 'd':
725 case 'H':
726 case 'm':
727 case 'M':
728 case 'S':
729 case 'W':
730 n++;
731 /* fall thru */
732 case 'w':
733 case '%':
734 break;
735 case 'f':
736 n += 8;
737 break;
738 case 'j':
739 n += 3;
740 break;
741 case 'Y':
742 n += 8;
743 break;
744 case 's':
745 case 'J':
746 n += 50;
747 break;
748 default:
749 return; /* ERROR. return a NULL */
750 }
751 i++;
752 }
753 }
754 if( n<sizeof(zBuf) ){
755 z = zBuf;
756 }else{
757 z = sqliteMalloc( n );
758 if( z==0 ) return;
759 }
760 computeJD(&x);
drhba212562004-01-08 02:17:31 +0000761 computeYMD_HMS(&x);
drh7014aff2003-11-01 01:53:53 +0000762 for(i=j=0; zFmt[i]; i++){
763 if( zFmt[i]!='%' ){
764 z[j++] = zFmt[i];
765 }else{
766 i++;
767 switch( zFmt[i] ){
768 case 'd': sprintf(&z[j],"%02d",x.D); j+=2; break;
769 case 'f': {
770 int s = x.s;
771 int ms = (x.s - s)*1000.0;
772 sprintf(&z[j],"%02d.%03d",s,ms);
773 j += strlen(&z[j]);
774 break;
775 }
776 case 'H': sprintf(&z[j],"%02d",x.h); j+=2; break;
777 case 'W': /* Fall thru */
778 case 'j': {
779 int n;
780 DateTime y = x;
781 y.validJD = 0;
782 y.M = 1;
783 y.D = 1;
784 computeJD(&y);
785 n = x.rJD - y.rJD + 1;
786 if( zFmt[i]=='W' ){
787 sprintf(&z[j],"%02d",(n+6)/7);
788 j += 2;
789 }else{
790 sprintf(&z[j],"%03d",n);
791 j += 3;
792 }
793 break;
794 }
795 case 'J': sprintf(&z[j],"%.16g",x.rJD); j+=strlen(&z[j]); break;
796 case 'm': sprintf(&z[j],"%02d",x.M); j+=2; break;
797 case 'M': sprintf(&z[j],"%02d",x.m); j+=2; break;
798 case 's': {
drhc5dd9fa2004-01-07 03:29:16 +0000799 sprintf(&z[j],"%d",(int)((x.rJD-2440587.5)*86400.0 + 0.5));
drh7014aff2003-11-01 01:53:53 +0000800 j += strlen(&z[j]);
801 break;
802 }
drhc5dd9fa2004-01-07 03:29:16 +0000803 case 'S': sprintf(&z[j],"%02d",(int)(x.s+0.5)); j+=2; break;
drh7014aff2003-11-01 01:53:53 +0000804 case 'w': z[j++] = (((int)(x.rJD+1.5)) % 7) + '0'; break;
805 case 'Y': sprintf(&z[j],"%04d",x.Y); j+=strlen(&z[j]); break;
806 case '%': z[j++] = '%'; break;
807 }
808 }
809 }
810 z[j] = 0;
811 sqlite_set_result_string(context, z, -1);
812 if( z!=zBuf ){
813 sqliteFree(z);
814 }
815}
816
817
818#endif /* !defined(SQLITE_OMIT_DATETIME_FUNCS) */
819
820/*
821** This function registered all of the above C functions as SQL
822** functions. This should be the only routine in this file with
823** external linkage.
824*/
825void sqliteRegisterDateTimeFunctions(sqlite *db){
826 static struct {
827 char *zName;
828 int nArg;
829 int dataType;
830 void (*xFunc)(sqlite_func*,int,const char**);
831 } aFuncs[] = {
832#ifndef SQLITE_OMIT_DATETIME_FUNCS
833 { "julianday", -1, SQLITE_NUMERIC, juliandayFunc },
834 { "date", -1, SQLITE_TEXT, dateFunc },
drhf586aa82003-12-23 16:34:12 +0000835 { "time", -1, SQLITE_TEXT, timeFunc },
drh7014aff2003-11-01 01:53:53 +0000836 { "datetime", -1, SQLITE_TEXT, datetimeFunc },
837 { "strftime", -1, SQLITE_TEXT, strftimeFunc },
838#endif
839 };
840 int i;
841
842 for(i=0; i<sizeof(aFuncs)/sizeof(aFuncs[0]); i++){
843 sqlite_create_function(db, aFuncs[i].zName,
844 aFuncs[i].nArg, aFuncs[i].xFunc, 0);
845 if( aFuncs[i].xFunc ){
846 sqlite_function_type(db, aFuncs[i].zName, aFuncs[i].dataType);
847 }
848 }
849}