blob: e7c438e619a606b67197d99c299fe6c95259ad7e [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**
drheb9a9e82004-02-22 17:49:32 +000019** $Id: date.c,v 1.12 2004/02/22 17:49:33 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/*
drheb9a9e82004-02-22 17:49:32 +000077** Convert zDate into one or more integers. Additional arguments
78** come in groups of 5 as follows:
79**
80** N number of digits in the integer
81** min minimum allowed value of the integer
82** max maximum allowed value of the integer
83** nextC first character after the integer
84** pVal where to write the integers value.
85**
86** Conversions continue until one with nextC==0 is encountered.
87** The function returns the number of successful conversions.
drh7014aff2003-11-01 01:53:53 +000088*/
drheb9a9e82004-02-22 17:49:32 +000089static int getDigits(const char *zDate, ...){
90 va_list ap;
91 int val;
92 int N;
93 int min;
94 int max;
95 int nextC;
96 int *pVal;
97 int cnt = 0;
98 va_start(ap, zDate);
99 do{
100 N = va_arg(ap, int);
101 min = va_arg(ap, int);
102 max = va_arg(ap, int);
103 nextC = va_arg(ap, int);
104 pVal = va_arg(ap, int*);
105 val = 0;
106 while( N-- ){
107 if( !isdigit(*zDate) ){
108 return cnt;
109 }
110 val = val*10 + *zDate - '0';
111 zDate++;
112 }
113 if( val<min || val>max || (nextC!=0 && nextC!=*zDate) ){
114 return cnt;
115 }
116 *pVal = val;
drh7014aff2003-11-01 01:53:53 +0000117 zDate++;
drheb9a9e82004-02-22 17:49:32 +0000118 cnt++;
119 }while( nextC );
120 return cnt;
drh7014aff2003-11-01 01:53:53 +0000121}
122
123/*
124** Read text from z[] and convert into a floating point number. Return
125** the number of digits converted.
126*/
127static int getValue(const char *z, double *pR){
drheb9a9e82004-02-22 17:49:32 +0000128 const char *zEnd;
129 *pR = sqliteAtoF(z, &zEnd);
130 return zEnd - z;
drh7014aff2003-11-01 01:53:53 +0000131}
132
133/*
134** Parse a timezone extension on the end of a date-time.
135** The extension is of the form:
136**
137** (+/-)HH:MM
138**
139** If the parse is successful, write the number of minutes
140** of change in *pnMin and return 0. If a parser error occurs,
141** return 0.
142**
143** A missing specifier is not considered an error.
144*/
145static int parseTimezone(const char *zDate, DateTime *p){
146 int sgn = 0;
147 int nHr, nMn;
148 while( isspace(*zDate) ){ zDate++; }
149 p->tz = 0;
150 if( *zDate=='-' ){
151 sgn = -1;
152 }else if( *zDate=='+' ){
153 sgn = +1;
154 }else{
155 return *zDate!=0;
156 }
157 zDate++;
drheb9a9e82004-02-22 17:49:32 +0000158 if( getDigits(zDate, 2, 0, 14, ':', &nHr, 2, 0, 59, 0, &nMn)!=2 ){
159 return 1;
160 }
161 zDate += 5;
drh7014aff2003-11-01 01:53:53 +0000162 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;
drheb9a9e82004-02-22 17:49:32 +0000177 if( getDigits(zDate, 2, 0, 24, ':', &h, 2, 0, 59, 0, &m)!=2 ){
178 return 1;
179 }
180 zDate += 5;
drh7014aff2003-11-01 01:53:53 +0000181 if( *zDate==':' ){
drheb9a9e82004-02-22 17:49:32 +0000182 zDate++;
183 if( getDigits(zDate, 2, 0, 59, 0, &s)!=1 ){
184 return 1;
185 }
186 zDate += 2;
drh7014aff2003-11-01 01:53:53 +0000187 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 }
drheb9a9e82004-02-22 17:49:32 +0000271 if( getDigits(zDate,4,0,9999,'-',&Y,2,1,12,'-',&M,2,1,31,0,&D)!=3 ){
272 return 1;
273 }
274 zDate += 10;
drh7014aff2003-11-01 01:53:53 +0000275 while( isspace(*zDate) ){ zDate++; }
drheb9a9e82004-02-22 17:49:32 +0000276 if( parseHhMmSs(zDate, p)==0 ){
277 /* We got the time */
drh7014aff2003-11-01 01:53:53 +0000278 }else if( *zDate==0 ){
279 p->validHMS = 0;
280 }else{
281 return 1;
282 }
283 p->validJD = 0;
284 p->validYMD = 1;
drh8eb2cce2004-02-21 03:28:18 +0000285 p->Y = neg ? -Y : Y;
drh7014aff2003-11-01 01:53:53 +0000286 p->M = M;
287 p->D = D;
288 if( p->validTZ ){
289 computeJD(p);
290 }
291 return 0;
292}
293
294/*
295** Attempt to parse the given string into a Julian Day Number. Return
296** the number of errors.
297**
298** The following are acceptable forms for the input string:
299**
300** YYYY-MM-DD HH:MM:SS.FFF +/-HH:MM
301** DDDD.DD
302** now
303**
304** In the first form, the +/-HH:MM is always optional. The fractional
305** seconds extension (the ".FFF") is optional. The seconds portion
306** (":SS.FFF") is option. The year and date can be omitted as long
307** as there is a time string. The time string can be omitted as long
308** as there is a year and date.
309*/
310static int parseDateOrTime(const char *zDate, DateTime *p){
drh7014aff2003-11-01 01:53:53 +0000311 memset(p, 0, sizeof(*p));
drh8eb2cce2004-02-21 03:28:18 +0000312 if( parseYyyyMmDd(zDate,p)==0 ){
drh7014aff2003-11-01 01:53:53 +0000313 return 0;
drh8eb2cce2004-02-21 03:28:18 +0000314 }else if( parseHhMmSs(zDate, p)==0 ){
315 return 0;
316 }else if( sqliteStrICmp(zDate,"now")==0){
drh7014aff2003-11-01 01:53:53 +0000317 double r;
318 if( sqliteOsCurrentTime(&r)==0 ){
319 p->rJD = r;
320 p->validJD = 1;
321 return 0;
322 }
323 return 1;
324 }else if( sqliteIsNumber(zDate) ){
drheb9a9e82004-02-22 17:49:32 +0000325 p->rJD = sqliteAtoF(zDate, 0);
drh7014aff2003-11-01 01:53:53 +0000326 p->validJD = 1;
327 return 0;
328 }
329 return 1;
330}
331
332/*
333** Compute the Year, Month, and Day from the julian day number.
334*/
335static void computeYMD(DateTime *p){
336 int Z, A, B, C, D, E, X1;
337 if( p->validYMD ) return;
338 Z = p->rJD + 0.5;
339 A = (Z - 1867216.25)/36524.25;
340 A = Z + 1 + A - (A/4);
341 B = A + 1524;
342 C = (B - 122.1)/365.25;
343 D = 365.25*C;
344 E = (B-D)/30.6001;
345 X1 = 30.6001*E;
346 p->D = B - D - X1;
347 p->M = E<14 ? E-1 : E-13;
348 p->Y = p->M>2 ? C - 4716 : C - 4715;
349 p->validYMD = 1;
350}
351
352/*
353** Compute the Hour, Minute, and Seconds from the julian day number.
354*/
355static void computeHMS(DateTime *p){
356 int Z, s;
357 if( p->validHMS ) return;
358 Z = p->rJD + 0.5;
359 s = (p->rJD + 0.5 - Z)*86400000.0 + 0.5;
360 p->s = 0.001*s;
361 s = p->s;
362 p->s -= s;
363 p->h = s/3600;
364 s -= p->h*3600;
365 p->m = s/60;
366 p->s += s - p->m*60;
367 p->validHMS = 1;
368}
369
370/*
drhba212562004-01-08 02:17:31 +0000371** Compute both YMD and HMS
372*/
373static void computeYMD_HMS(DateTime *p){
374 computeYMD(p);
375 computeHMS(p);
376}
377
378/*
379** Clear the YMD and HMS and the TZ
380*/
381static void clearYMD_HMS_TZ(DateTime *p){
382 p->validYMD = 0;
383 p->validHMS = 0;
384 p->validTZ = 0;
385}
386
387/*
drh7091cb02003-12-23 16:22:18 +0000388** Compute the difference (in days) between localtime and UTC (a.k.a. GMT)
389** for the time value p where p is in UTC.
390*/
391static double localtimeOffset(DateTime *p){
392 DateTime x, y;
393 time_t t;
394 struct tm *pTm;
drh7091cb02003-12-23 16:22:18 +0000395 x = *p;
drhba212562004-01-08 02:17:31 +0000396 computeYMD_HMS(&x);
drh7091cb02003-12-23 16:22:18 +0000397 if( x.Y<1971 || x.Y>=2038 ){
398 x.Y = 2000;
399 x.M = 1;
400 x.D = 1;
401 x.h = 0;
402 x.m = 0;
403 x.s = 0.0;
404 } else {
405 int s = x.s + 0.5;
406 x.s = s;
407 }
408 x.tz = 0;
409 x.validJD = 0;
410 computeJD(&x);
411 t = (x.rJD-2440587.5)*86400.0 + 0.5;
412 sqliteOsEnterMutex();
413 pTm = localtime(&t);
414 y.Y = pTm->tm_year + 1900;
415 y.M = pTm->tm_mon + 1;
416 y.D = pTm->tm_mday;
417 y.h = pTm->tm_hour;
418 y.m = pTm->tm_min;
419 y.s = pTm->tm_sec;
420 sqliteOsLeaveMutex();
421 y.validYMD = 1;
422 y.validHMS = 1;
423 y.validJD = 0;
424 y.validTZ = 0;
425 computeJD(&y);
drh7091cb02003-12-23 16:22:18 +0000426 return y.rJD - x.rJD;
427}
428
429/*
drh7014aff2003-11-01 01:53:53 +0000430** Process a modifier to a date-time stamp. The modifiers are
431** as follows:
432**
433** NNN days
434** NNN hours
435** NNN minutes
436** NNN.NNNN seconds
437** NNN months
438** NNN years
439** start of month
440** start of year
441** start of week
442** start of day
443** weekday N
444** unixepoch
drh7091cb02003-12-23 16:22:18 +0000445** localtime
446** utc
drh7014aff2003-11-01 01:53:53 +0000447**
448** Return 0 on success and 1 if there is any kind of error.
449*/
450static int parseModifier(const char *zMod, DateTime *p){
451 int rc = 1;
452 int n;
453 double r;
drh4d5b8362004-01-17 01:16:21 +0000454 char *z, zBuf[30];
455 z = zBuf;
456 for(n=0; n<sizeof(zBuf)-1 && zMod[n]; n++){
drh7014aff2003-11-01 01:53:53 +0000457 z[n] = tolower(zMod[n]);
458 }
459 z[n] = 0;
460 switch( z[0] ){
drh7091cb02003-12-23 16:22:18 +0000461 case 'l': {
462 /* localtime
463 **
464 ** Assuming the current time value is UTC (a.k.a. GMT), shift it to
465 ** show local time.
466 */
467 if( strcmp(z, "localtime")==0 ){
468 computeJD(p);
469 p->rJD += localtimeOffset(p);
drhba212562004-01-08 02:17:31 +0000470 clearYMD_HMS_TZ(p);
drh7091cb02003-12-23 16:22:18 +0000471 rc = 0;
472 }
473 break;
474 }
drh7014aff2003-11-01 01:53:53 +0000475 case 'u': {
476 /*
477 ** unixepoch
478 **
479 ** Treat the current value of p->rJD as the number of
480 ** seconds since 1970. Convert to a real julian day number.
481 */
482 if( strcmp(z, "unixepoch")==0 && p->validJD ){
483 p->rJD = p->rJD/86400.0 + 2440587.5;
drhba212562004-01-08 02:17:31 +0000484 clearYMD_HMS_TZ(p);
drh7014aff2003-11-01 01:53:53 +0000485 rc = 0;
drh7091cb02003-12-23 16:22:18 +0000486 }else if( strcmp(z, "utc")==0 ){
487 double c1;
488 computeJD(p);
489 c1 = localtimeOffset(p);
490 p->rJD -= c1;
drhba212562004-01-08 02:17:31 +0000491 clearYMD_HMS_TZ(p);
drh7091cb02003-12-23 16:22:18 +0000492 p->rJD += c1 - localtimeOffset(p);
drh7091cb02003-12-23 16:22:18 +0000493 rc = 0;
drh7014aff2003-11-01 01:53:53 +0000494 }
495 break;
496 }
497 case 'w': {
498 /*
499 ** weekday N
500 **
drhc5dd9fa2004-01-07 03:29:16 +0000501 ** Move the date to the same time on the next occurrance of
drh7014aff2003-11-01 01:53:53 +0000502 ** weekday N where 0==Sunday, 1==Monday, and so forth. If the
drhc5dd9fa2004-01-07 03:29:16 +0000503 ** date is already on the appropriate weekday, this is a no-op.
drh7014aff2003-11-01 01:53:53 +0000504 */
505 if( strncmp(z, "weekday ", 8)==0 && getValue(&z[8],&r)>0
506 && (n=r)==r && n>=0 && r<7 ){
507 int Z;
drhba212562004-01-08 02:17:31 +0000508 computeYMD_HMS(p);
drh7014aff2003-11-01 01:53:53 +0000509 p->validTZ = 0;
510 p->validJD = 0;
511 computeJD(p);
512 Z = p->rJD + 1.5;
513 Z %= 7;
514 if( Z>n ) Z -= 7;
515 p->rJD += n - Z;
drhba212562004-01-08 02:17:31 +0000516 clearYMD_HMS_TZ(p);
drh7014aff2003-11-01 01:53:53 +0000517 rc = 0;
518 }
519 break;
520 }
521 case 's': {
522 /*
523 ** start of TTTTT
524 **
525 ** Move the date backwards to the beginning of the current day,
526 ** or month or year.
527 */
528 if( strncmp(z, "start of ", 9)!=0 ) break;
drh4d5b8362004-01-17 01:16:21 +0000529 z += 9;
drh7014aff2003-11-01 01:53:53 +0000530 computeYMD(p);
531 p->validHMS = 1;
532 p->h = p->m = 0;
533 p->s = 0.0;
534 p->validTZ = 0;
535 p->validJD = 0;
drh4d5b8362004-01-17 01:16:21 +0000536 if( strcmp(z,"month")==0 ){
drh7014aff2003-11-01 01:53:53 +0000537 p->D = 1;
538 rc = 0;
drh4d5b8362004-01-17 01:16:21 +0000539 }else if( strcmp(z,"year")==0 ){
drh7014aff2003-11-01 01:53:53 +0000540 computeYMD(p);
541 p->M = 1;
542 p->D = 1;
543 rc = 0;
drh4d5b8362004-01-17 01:16:21 +0000544 }else if( strcmp(z,"day")==0 ){
drh7014aff2003-11-01 01:53:53 +0000545 rc = 0;
546 }
547 break;
548 }
549 case '+':
550 case '-':
551 case '0':
552 case '1':
553 case '2':
554 case '3':
555 case '4':
556 case '5':
557 case '6':
558 case '7':
559 case '8':
560 case '9': {
561 n = getValue(z, &r);
562 if( n<=0 ) break;
drh4d5b8362004-01-17 01:16:21 +0000563 z += n;
564 while( isspace(z[0]) ) z++;
565 n = strlen(z);
drh7014aff2003-11-01 01:53:53 +0000566 if( n>10 || n<3 ) break;
drh7014aff2003-11-01 01:53:53 +0000567 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 ){
drh7014aff2003-11-01 01:53:53 +0000573 p->rJD += r/24.0;
574 }else if( n==6 && strcmp(z,"minute")==0 ){
drh7014aff2003-11-01 01:53:53 +0000575 p->rJD += r/(24.0*60.0);
576 }else if( n==6 && strcmp(z,"second")==0 ){
drh7014aff2003-11-01 01:53:53 +0000577 p->rJD += r/(24.0*60.0*60.0);
578 }else if( n==5 && strcmp(z,"month")==0 ){
579 int x, y;
drhba212562004-01-08 02:17:31 +0000580 computeYMD_HMS(p);
drh7014aff2003-11-01 01:53:53 +0000581 p->M += r;
582 x = p->M>0 ? (p->M-1)/12 : (p->M-12)/12;
583 p->Y += x;
584 p->M -= x*12;
585 p->validJD = 0;
586 computeJD(p);
587 y = r;
588 if( y!=r ){
589 p->rJD += (r - y)*30.0;
590 }
591 }else if( n==4 && strcmp(z,"year")==0 ){
drhba212562004-01-08 02:17:31 +0000592 computeYMD_HMS(p);
drh7014aff2003-11-01 01:53:53 +0000593 p->Y += r;
594 p->validJD = 0;
595 computeJD(p);
596 }else{
597 rc = 1;
598 }
drhba212562004-01-08 02:17:31 +0000599 clearYMD_HMS_TZ(p);
drh7014aff2003-11-01 01:53:53 +0000600 break;
601 }
602 default: {
603 break;
604 }
605 }
606 return rc;
607}
608
609/*
610** Process time function arguments. argv[0] is a date-time stamp.
611** argv[1] and following are modifiers. Parse them all and write
612** the resulting time into the DateTime structure p. Return 0
613** on success and 1 if there are any errors.
614*/
615static int isDate(int argc, const char **argv, DateTime *p){
616 int i;
617 if( argc==0 ) return 1;
drhf586aa82003-12-23 16:34:12 +0000618 if( argv[0]==0 || parseDateOrTime(argv[0], p) ) return 1;
drh7014aff2003-11-01 01:53:53 +0000619 for(i=1; i<argc; i++){
drhf586aa82003-12-23 16:34:12 +0000620 if( argv[i]==0 || parseModifier(argv[i], p) ) return 1;
drh7014aff2003-11-01 01:53:53 +0000621 }
622 return 0;
623}
624
625
626/*
627** The following routines implement the various date and time functions
628** of SQLite.
629*/
630
631/*
632** julianday( TIMESTRING, MOD, MOD, ...)
633**
634** Return the julian day number of the date specified in the arguments
635*/
636static void juliandayFunc(sqlite_func *context, int argc, const char **argv){
637 DateTime x;
638 if( isDate(argc, argv, &x)==0 ){
639 computeJD(&x);
640 sqlite_set_result_double(context, x.rJD);
641 }
642}
643
644/*
645** datetime( TIMESTRING, MOD, MOD, ...)
646**
647** Return YYYY-MM-DD HH:MM:SS
648*/
649static void datetimeFunc(sqlite_func *context, int argc, const char **argv){
650 DateTime x;
651 if( isDate(argc, argv, &x)==0 ){
652 char zBuf[100];
drhba212562004-01-08 02:17:31 +0000653 computeYMD_HMS(&x);
drh7014aff2003-11-01 01:53:53 +0000654 sprintf(zBuf, "%04d-%02d-%02d %02d:%02d:%02d",x.Y, x.M, x.D, x.h, x.m,
655 (int)(x.s));
656 sqlite_set_result_string(context, zBuf, -1);
657 }
658}
659
660/*
661** time( TIMESTRING, MOD, MOD, ...)
662**
663** Return HH:MM:SS
664*/
665static void timeFunc(sqlite_func *context, int argc, const char **argv){
666 DateTime x;
667 if( isDate(argc, argv, &x)==0 ){
668 char zBuf[100];
669 computeHMS(&x);
670 sprintf(zBuf, "%02d:%02d:%02d", x.h, x.m, (int)x.s);
671 sqlite_set_result_string(context, zBuf, -1);
672 }
673}
674
675/*
676** date( TIMESTRING, MOD, MOD, ...)
677**
678** Return YYYY-MM-DD
679*/
680static void dateFunc(sqlite_func *context, int argc, const char **argv){
681 DateTime x;
682 if( isDate(argc, argv, &x)==0 ){
683 char zBuf[100];
684 computeYMD(&x);
685 sprintf(zBuf, "%04d-%02d-%02d", x.Y, x.M, x.D);
686 sqlite_set_result_string(context, zBuf, -1);
687 }
688}
689
690/*
691** strftime( FORMAT, TIMESTRING, MOD, MOD, ...)
692**
693** Return a string described by FORMAT. Conversions as follows:
694**
695** %d day of month
696** %f ** fractional seconds SS.SSS
697** %H hour 00-24
698** %j day of year 000-366
699** %J ** Julian day number
700** %m month 01-12
701** %M minute 00-59
702** %s seconds since 1970-01-01
703** %S seconds 00-59
704** %w day of week 0-6 sunday==0
705** %W week of year 00-53
706** %Y year 0000-9999
707** %% %
708*/
709static void strftimeFunc(sqlite_func *context, int argc, const char **argv){
710 DateTime x;
711 int n, i, j;
712 char *z;
713 const char *zFmt = argv[0];
714 char zBuf[100];
drhf586aa82003-12-23 16:34:12 +0000715 if( argv[0]==0 || isDate(argc-1, argv+1, &x) ) return;
drh7014aff2003-11-01 01:53:53 +0000716 for(i=0, n=1; zFmt[i]; i++, n++){
717 if( zFmt[i]=='%' ){
718 switch( zFmt[i+1] ){
719 case 'd':
720 case 'H':
721 case 'm':
722 case 'M':
723 case 'S':
724 case 'W':
725 n++;
726 /* fall thru */
727 case 'w':
728 case '%':
729 break;
730 case 'f':
731 n += 8;
732 break;
733 case 'j':
734 n += 3;
735 break;
736 case 'Y':
737 n += 8;
738 break;
739 case 's':
740 case 'J':
741 n += 50;
742 break;
743 default:
744 return; /* ERROR. return a NULL */
745 }
746 i++;
747 }
748 }
749 if( n<sizeof(zBuf) ){
750 z = zBuf;
751 }else{
752 z = sqliteMalloc( n );
753 if( z==0 ) return;
754 }
755 computeJD(&x);
drhba212562004-01-08 02:17:31 +0000756 computeYMD_HMS(&x);
drh7014aff2003-11-01 01:53:53 +0000757 for(i=j=0; zFmt[i]; i++){
758 if( zFmt[i]!='%' ){
759 z[j++] = zFmt[i];
760 }else{
761 i++;
762 switch( zFmt[i] ){
763 case 'd': sprintf(&z[j],"%02d",x.D); j+=2; break;
764 case 'f': {
765 int s = x.s;
766 int ms = (x.s - s)*1000.0;
767 sprintf(&z[j],"%02d.%03d",s,ms);
768 j += strlen(&z[j]);
769 break;
770 }
771 case 'H': sprintf(&z[j],"%02d",x.h); j+=2; break;
772 case 'W': /* Fall thru */
773 case 'j': {
774 int n;
775 DateTime y = x;
776 y.validJD = 0;
777 y.M = 1;
778 y.D = 1;
779 computeJD(&y);
780 n = x.rJD - y.rJD + 1;
781 if( zFmt[i]=='W' ){
782 sprintf(&z[j],"%02d",(n+6)/7);
783 j += 2;
784 }else{
785 sprintf(&z[j],"%03d",n);
786 j += 3;
787 }
788 break;
789 }
790 case 'J': sprintf(&z[j],"%.16g",x.rJD); j+=strlen(&z[j]); break;
791 case 'm': sprintf(&z[j],"%02d",x.M); j+=2; break;
792 case 'M': sprintf(&z[j],"%02d",x.m); j+=2; break;
793 case 's': {
drhc5dd9fa2004-01-07 03:29:16 +0000794 sprintf(&z[j],"%d",(int)((x.rJD-2440587.5)*86400.0 + 0.5));
drh7014aff2003-11-01 01:53:53 +0000795 j += strlen(&z[j]);
796 break;
797 }
drhc5dd9fa2004-01-07 03:29:16 +0000798 case 'S': sprintf(&z[j],"%02d",(int)(x.s+0.5)); j+=2; break;
drh7014aff2003-11-01 01:53:53 +0000799 case 'w': z[j++] = (((int)(x.rJD+1.5)) % 7) + '0'; break;
800 case 'Y': sprintf(&z[j],"%04d",x.Y); j+=strlen(&z[j]); break;
801 case '%': z[j++] = '%'; break;
802 }
803 }
804 }
805 z[j] = 0;
806 sqlite_set_result_string(context, z, -1);
807 if( z!=zBuf ){
808 sqliteFree(z);
809 }
810}
811
812
813#endif /* !defined(SQLITE_OMIT_DATETIME_FUNCS) */
814
815/*
816** This function registered all of the above C functions as SQL
817** functions. This should be the only routine in this file with
818** external linkage.
819*/
820void sqliteRegisterDateTimeFunctions(sqlite *db){
821 static struct {
822 char *zName;
823 int nArg;
824 int dataType;
825 void (*xFunc)(sqlite_func*,int,const char**);
826 } aFuncs[] = {
827#ifndef SQLITE_OMIT_DATETIME_FUNCS
828 { "julianday", -1, SQLITE_NUMERIC, juliandayFunc },
829 { "date", -1, SQLITE_TEXT, dateFunc },
drhf586aa82003-12-23 16:34:12 +0000830 { "time", -1, SQLITE_TEXT, timeFunc },
drh7014aff2003-11-01 01:53:53 +0000831 { "datetime", -1, SQLITE_TEXT, datetimeFunc },
832 { "strftime", -1, SQLITE_TEXT, strftimeFunc },
833#endif
834 };
835 int i;
836
837 for(i=0; i<sizeof(aFuncs)/sizeof(aFuncs[0]); i++){
838 sqlite_create_function(db, aFuncs[i].zName,
839 aFuncs[i].nArg, aFuncs[i].xFunc, 0);
840 if( aFuncs[i].xFunc ){
841 sqlite_function_type(db, aFuncs[i].zName, aFuncs[i].dataType);
842 }
843 }
844}