blob: b4ff3509b5ee9b6adc23c8ed549054f16ca2abbe [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
danielk19774adee202004-05-08 08:23:19 +000016** sqlite3RegisterDateTimeFunctions() found at the bottom of the file.
drh7014aff2003-11-01 01:53:53 +000017** All other code has file scope.
18**
drh24b010f2006-01-13 01:17:21 +000019** $Id: date.c,v 1.50 2006/01/13 01:17: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*/
dougcurrieae534182003-12-24 01:41:19 +000050#include "sqliteInt.h"
drheb206252004-10-01 02:00:31 +000051#include "os.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-- ){
drh4c755c02004-08-08 20:22:17 +0000107 if( !isdigit(*(u8*)zDate) ){
drheb9a9e82004-02-22 17:49:32 +0000108 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 );
drh24b010f2006-01-13 01:17:21 +0000120 va_end(ap);
drheb9a9e82004-02-22 17:49:32 +0000121 return cnt;
drh7014aff2003-11-01 01:53:53 +0000122}
123
124/*
125** Read text from z[] and convert into a floating point number. Return
126** the number of digits converted.
127*/
drh487e2622005-06-25 18:42:14 +0000128#define getValue sqlite3AtoF
drh7014aff2003-11-01 01:53:53 +0000129
130/*
131** Parse a timezone extension on the end of a date-time.
132** The extension is of the form:
133**
134** (+/-)HH:MM
135**
136** If the parse is successful, write the number of minutes
137** of change in *pnMin and return 0. If a parser error occurs,
138** return 0.
139**
140** A missing specifier is not considered an error.
141*/
142static int parseTimezone(const char *zDate, DateTime *p){
143 int sgn = 0;
144 int nHr, nMn;
drh4c755c02004-08-08 20:22:17 +0000145 while( isspace(*(u8*)zDate) ){ zDate++; }
drh7014aff2003-11-01 01:53:53 +0000146 p->tz = 0;
147 if( *zDate=='-' ){
148 sgn = -1;
149 }else if( *zDate=='+' ){
150 sgn = +1;
151 }else{
152 return *zDate!=0;
153 }
154 zDate++;
drheb9a9e82004-02-22 17:49:32 +0000155 if( getDigits(zDate, 2, 0, 14, ':', &nHr, 2, 0, 59, 0, &nMn)!=2 ){
156 return 1;
157 }
158 zDate += 5;
drh7014aff2003-11-01 01:53:53 +0000159 p->tz = sgn*(nMn + nHr*60);
drh4c755c02004-08-08 20:22:17 +0000160 while( isspace(*(u8*)zDate) ){ zDate++; }
drh7014aff2003-11-01 01:53:53 +0000161 return *zDate!=0;
162}
163
164/*
165** Parse times of the form HH:MM or HH:MM:SS or HH:MM:SS.FFFF.
166** The HH, MM, and SS must each be exactly 2 digits. The
167** fractional seconds FFFF can be one or more digits.
168**
169** Return 1 if there is a parsing error and 0 on success.
170*/
171static int parseHhMmSs(const char *zDate, DateTime *p){
172 int h, m, s;
173 double ms = 0.0;
drheb9a9e82004-02-22 17:49:32 +0000174 if( getDigits(zDate, 2, 0, 24, ':', &h, 2, 0, 59, 0, &m)!=2 ){
175 return 1;
176 }
177 zDate += 5;
drh7014aff2003-11-01 01:53:53 +0000178 if( *zDate==':' ){
drheb9a9e82004-02-22 17:49:32 +0000179 zDate++;
180 if( getDigits(zDate, 2, 0, 59, 0, &s)!=1 ){
181 return 1;
182 }
183 zDate += 2;
drh4c755c02004-08-08 20:22:17 +0000184 if( *zDate=='.' && isdigit((u8)zDate[1]) ){
drh7014aff2003-11-01 01:53:53 +0000185 double rScale = 1.0;
186 zDate++;
drh4c755c02004-08-08 20:22:17 +0000187 while( isdigit(*(u8*)zDate) ){
drh7014aff2003-11-01 01:53:53 +0000188 ms = ms*10.0 + *zDate - '0';
189 rScale *= 10.0;
190 zDate++;
191 }
192 ms /= rScale;
193 }
194 }else{
195 s = 0;
196 }
197 p->validJD = 0;
198 p->validHMS = 1;
199 p->h = h;
200 p->m = m;
201 p->s = s + ms;
202 if( parseTimezone(zDate, p) ) return 1;
203 p->validTZ = p->tz!=0;
204 return 0;
205}
206
207/*
208** Convert from YYYY-MM-DD HH:MM:SS to julian day. We always assume
209** that the YYYY-MM-DD is according to the Gregorian calendar.
210**
211** Reference: Meeus page 61
212*/
213static void computeJD(DateTime *p){
214 int Y, M, D, A, B, X1, X2;
215
216 if( p->validJD ) return;
217 if( p->validYMD ){
218 Y = p->Y;
219 M = p->M;
220 D = p->D;
221 }else{
drhba212562004-01-08 02:17:31 +0000222 Y = 2000; /* If no YMD specified, assume 2000-Jan-01 */
drh7014aff2003-11-01 01:53:53 +0000223 M = 1;
224 D = 1;
225 }
226 if( M<=2 ){
227 Y--;
228 M += 12;
229 }
230 A = Y/100;
231 B = 2 - A + (A/4);
232 X1 = 365.25*(Y+4716);
233 X2 = 30.6001*(M+1);
234 p->rJD = X1 + X2 + D + B - 1524.5;
235 p->validJD = 1;
236 p->validYMD = 0;
237 if( p->validHMS ){
238 p->rJD += (p->h*3600.0 + p->m*60.0 + p->s)/86400.0;
239 if( p->validTZ ){
drh57391032006-01-09 00:18:02 +0000240 p->rJD -= p->tz*60/86400.0;
drh7014aff2003-11-01 01:53:53 +0000241 p->validHMS = 0;
242 p->validTZ = 0;
243 }
244 }
245}
246
247/*
248** Parse dates of the form
249**
250** YYYY-MM-DD HH:MM:SS.FFF
251** YYYY-MM-DD HH:MM:SS
252** YYYY-MM-DD HH:MM
253** YYYY-MM-DD
254**
255** Write the result into the DateTime structure and return 0
256** on success and 1 if the input string is not a well-formed
257** date.
258*/
259static int parseYyyyMmDd(const char *zDate, DateTime *p){
drh8eb2cce2004-02-21 03:28:18 +0000260 int Y, M, D, neg;
drh7014aff2003-11-01 01:53:53 +0000261
drh8eb2cce2004-02-21 03:28:18 +0000262 if( zDate[0]=='-' ){
263 zDate++;
264 neg = 1;
265 }else{
266 neg = 0;
267 }
drheb9a9e82004-02-22 17:49:32 +0000268 if( getDigits(zDate,4,0,9999,'-',&Y,2,1,12,'-',&M,2,1,31,0,&D)!=3 ){
269 return 1;
270 }
271 zDate += 10;
drh4cb29b42005-03-21 00:43:44 +0000272 while( isspace(*(u8*)zDate) || 'T'==*(u8*)zDate ){ zDate++; }
drheb9a9e82004-02-22 17:49:32 +0000273 if( parseHhMmSs(zDate, p)==0 ){
274 /* We got the time */
drh7014aff2003-11-01 01:53:53 +0000275 }else if( *zDate==0 ){
276 p->validHMS = 0;
277 }else{
278 return 1;
279 }
280 p->validJD = 0;
281 p->validYMD = 1;
drh8eb2cce2004-02-21 03:28:18 +0000282 p->Y = neg ? -Y : Y;
drh7014aff2003-11-01 01:53:53 +0000283 p->M = M;
284 p->D = D;
285 if( p->validTZ ){
286 computeJD(p);
287 }
288 return 0;
289}
290
291/*
292** Attempt to parse the given string into a Julian Day Number. Return
293** the number of errors.
294**
295** The following are acceptable forms for the input string:
296**
297** YYYY-MM-DD HH:MM:SS.FFF +/-HH:MM
298** DDDD.DD
299** now
300**
301** In the first form, the +/-HH:MM is always optional. The fractional
302** seconds extension (the ".FFF") is optional. The seconds portion
303** (":SS.FFF") is option. The year and date can be omitted as long
304** as there is a time string. The time string can be omitted as long
305** as there is a year and date.
306*/
307static int parseDateOrTime(const char *zDate, DateTime *p){
drh7014aff2003-11-01 01:53:53 +0000308 memset(p, 0, sizeof(*p));
drh8eb2cce2004-02-21 03:28:18 +0000309 if( parseYyyyMmDd(zDate,p)==0 ){
drh7014aff2003-11-01 01:53:53 +0000310 return 0;
drh8eb2cce2004-02-21 03:28:18 +0000311 }else if( parseHhMmSs(zDate, p)==0 ){
312 return 0;
danielk19774adee202004-05-08 08:23:19 +0000313 }else if( sqlite3StrICmp(zDate,"now")==0){
drh7014aff2003-11-01 01:53:53 +0000314 double r;
drh66560ad2006-01-06 14:32:19 +0000315 sqlite3OsCurrentTime(&r);
drh018d1a42005-01-15 01:52:31 +0000316 p->rJD = r;
317 p->validJD = 1;
318 return 0;
danielk1977dc8453f2004-06-12 00:42:34 +0000319 }else if( sqlite3IsNumber(zDate, 0, SQLITE_UTF8) ){
drh487e2622005-06-25 18:42:14 +0000320 getValue(zDate, &p->rJD);
drh7014aff2003-11-01 01:53:53 +0000321 p->validJD = 1;
322 return 0;
323 }
324 return 1;
325}
326
327/*
328** Compute the Year, Month, and Day from the julian day number.
329*/
330static void computeYMD(DateTime *p){
331 int Z, A, B, C, D, E, X1;
332 if( p->validYMD ) return;
drh33a9ad22004-02-29 00:40:32 +0000333 if( !p->validJD ){
334 p->Y = 2000;
335 p->M = 1;
336 p->D = 1;
337 }else{
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 }
drh7014aff2003-11-01 01:53:53 +0000350 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;
drh66560ad2006-01-06 14:32:19 +0000413 sqlite3OsEnterMutex();
drh7091cb02003-12-23 16:22:18 +0000414 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;
drh66560ad2006-01-06 14:32:19 +0000421 sqlite3OsLeaveMutex();
drh7091cb02003-12-23 16:22:18 +0000422 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 **
drh181fc992004-08-17 10:42:54 +0000502 ** Move the date to the same time on the next occurrence 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;
drh33a9ad22004-02-29 00:40:32 +0000564 if( z[n]==':' ){
565 /* A modifier of the form (+|-)HH:MM:SS.FFF adds (or subtracts) the
566 ** specified number of hours, minutes, seconds, and fractional seconds
567 ** to the time. The ".FFF" may be omitted. The ":SS.FFF" may be
568 ** omitted.
569 */
570 const char *z2 = z;
571 DateTime tx;
572 int day;
drh4c755c02004-08-08 20:22:17 +0000573 if( !isdigit(*(u8*)z2) ) z2++;
drh33a9ad22004-02-29 00:40:32 +0000574 memset(&tx, 0, sizeof(tx));
575 if( parseHhMmSs(z2, &tx) ) break;
576 computeJD(&tx);
drh0d131ab2004-02-29 01:08:17 +0000577 tx.rJD -= 0.5;
drh33a9ad22004-02-29 00:40:32 +0000578 day = (int)tx.rJD;
drhb6829e92004-02-29 00:50:33 +0000579 tx.rJD -= day;
drhb6829e92004-02-29 00:50:33 +0000580 if( z[0]=='-' ) tx.rJD = -tx.rJD;
drh0d131ab2004-02-29 01:08:17 +0000581 computeJD(p);
582 clearYMD_HMS_TZ(p);
583 p->rJD += tx.rJD;
drh33a9ad22004-02-29 00:40:32 +0000584 rc = 0;
585 break;
586 }
drh4d5b8362004-01-17 01:16:21 +0000587 z += n;
drh4c755c02004-08-08 20:22:17 +0000588 while( isspace(*(u8*)z) ) z++;
drh4d5b8362004-01-17 01:16:21 +0000589 n = strlen(z);
drh7014aff2003-11-01 01:53:53 +0000590 if( n>10 || n<3 ) break;
drh7014aff2003-11-01 01:53:53 +0000591 if( z[n-1]=='s' ){ z[n-1] = 0; n--; }
592 computeJD(p);
593 rc = 0;
594 if( n==3 && strcmp(z,"day")==0 ){
595 p->rJD += r;
596 }else if( n==4 && strcmp(z,"hour")==0 ){
drh7014aff2003-11-01 01:53:53 +0000597 p->rJD += r/24.0;
598 }else if( n==6 && strcmp(z,"minute")==0 ){
drh7014aff2003-11-01 01:53:53 +0000599 p->rJD += r/(24.0*60.0);
600 }else if( n==6 && strcmp(z,"second")==0 ){
drh7014aff2003-11-01 01:53:53 +0000601 p->rJD += r/(24.0*60.0*60.0);
602 }else if( n==5 && strcmp(z,"month")==0 ){
603 int x, y;
drhba212562004-01-08 02:17:31 +0000604 computeYMD_HMS(p);
drh7014aff2003-11-01 01:53:53 +0000605 p->M += r;
606 x = p->M>0 ? (p->M-1)/12 : (p->M-12)/12;
607 p->Y += x;
608 p->M -= x*12;
609 p->validJD = 0;
610 computeJD(p);
611 y = r;
612 if( y!=r ){
613 p->rJD += (r - y)*30.0;
614 }
615 }else if( n==4 && strcmp(z,"year")==0 ){
drhba212562004-01-08 02:17:31 +0000616 computeYMD_HMS(p);
drh7014aff2003-11-01 01:53:53 +0000617 p->Y += r;
618 p->validJD = 0;
619 computeJD(p);
620 }else{
621 rc = 1;
622 }
drhba212562004-01-08 02:17:31 +0000623 clearYMD_HMS_TZ(p);
drh7014aff2003-11-01 01:53:53 +0000624 break;
625 }
626 default: {
627 break;
628 }
629 }
630 return rc;
631}
632
633/*
634** Process time function arguments. argv[0] is a date-time stamp.
635** argv[1] and following are modifiers. Parse them all and write
636** the resulting time into the DateTime structure p. Return 0
637** on success and 1 if there are any errors.
638*/
danielk197751ad0ec2004-05-24 12:39:02 +0000639static int isDate(int argc, sqlite3_value **argv, DateTime *p){
drh7014aff2003-11-01 01:53:53 +0000640 int i;
641 if( argc==0 ) return 1;
drh9c054832004-05-31 18:51:57 +0000642 if( SQLITE_NULL==sqlite3_value_type(argv[0]) ||
drh2646da72005-12-09 20:02:05 +0000643 parseDateOrTime((char*)sqlite3_value_text(argv[0]), p) ) return 1;
drh7014aff2003-11-01 01:53:53 +0000644 for(i=1; i<argc; i++){
drh9c054832004-05-31 18:51:57 +0000645 if( SQLITE_NULL==sqlite3_value_type(argv[i]) ||
drh2646da72005-12-09 20:02:05 +0000646 parseModifier((char*)sqlite3_value_text(argv[i]), p) ) return 1;
drh7014aff2003-11-01 01:53:53 +0000647 }
648 return 0;
649}
650
651
652/*
653** The following routines implement the various date and time functions
654** of SQLite.
655*/
656
657/*
658** julianday( TIMESTRING, MOD, MOD, ...)
659**
660** Return the julian day number of the date specified in the arguments
661*/
drhf9b596e2004-05-26 16:54:42 +0000662static void juliandayFunc(
663 sqlite3_context *context,
664 int argc,
665 sqlite3_value **argv
666){
drh7014aff2003-11-01 01:53:53 +0000667 DateTime x;
668 if( isDate(argc, argv, &x)==0 ){
669 computeJD(&x);
danielk19777e18c252004-05-25 11:47:24 +0000670 sqlite3_result_double(context, x.rJD);
drh7014aff2003-11-01 01:53:53 +0000671 }
672}
673
674/*
675** datetime( TIMESTRING, MOD, MOD, ...)
676**
677** Return YYYY-MM-DD HH:MM:SS
678*/
drhf9b596e2004-05-26 16:54:42 +0000679static void datetimeFunc(
680 sqlite3_context *context,
681 int argc,
682 sqlite3_value **argv
683){
drh7014aff2003-11-01 01:53:53 +0000684 DateTime x;
685 if( isDate(argc, argv, &x)==0 ){
686 char zBuf[100];
drhba212562004-01-08 02:17:31 +0000687 computeYMD_HMS(&x);
drh7014aff2003-11-01 01:53:53 +0000688 sprintf(zBuf, "%04d-%02d-%02d %02d:%02d:%02d",x.Y, x.M, x.D, x.h, x.m,
689 (int)(x.s));
danielk1977d8123362004-06-12 09:25:12 +0000690 sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
drh7014aff2003-11-01 01:53:53 +0000691 }
692}
693
694/*
695** time( TIMESTRING, MOD, MOD, ...)
696**
697** Return HH:MM:SS
698*/
drhf9b596e2004-05-26 16:54:42 +0000699static void timeFunc(
700 sqlite3_context *context,
701 int argc,
702 sqlite3_value **argv
703){
drh7014aff2003-11-01 01:53:53 +0000704 DateTime x;
705 if( isDate(argc, argv, &x)==0 ){
706 char zBuf[100];
707 computeHMS(&x);
708 sprintf(zBuf, "%02d:%02d:%02d", x.h, x.m, (int)x.s);
danielk1977d8123362004-06-12 09:25:12 +0000709 sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
drh7014aff2003-11-01 01:53:53 +0000710 }
711}
712
713/*
714** date( TIMESTRING, MOD, MOD, ...)
715**
716** Return YYYY-MM-DD
717*/
drhf9b596e2004-05-26 16:54:42 +0000718static void dateFunc(
719 sqlite3_context *context,
720 int argc,
721 sqlite3_value **argv
722){
drh7014aff2003-11-01 01:53:53 +0000723 DateTime x;
724 if( isDate(argc, argv, &x)==0 ){
725 char zBuf[100];
726 computeYMD(&x);
727 sprintf(zBuf, "%04d-%02d-%02d", x.Y, x.M, x.D);
danielk1977d8123362004-06-12 09:25:12 +0000728 sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
drh7014aff2003-11-01 01:53:53 +0000729 }
730}
731
732/*
733** strftime( FORMAT, TIMESTRING, MOD, MOD, ...)
734**
735** Return a string described by FORMAT. Conversions as follows:
736**
737** %d day of month
738** %f ** fractional seconds SS.SSS
739** %H hour 00-24
740** %j day of year 000-366
741** %J ** Julian day number
742** %m month 01-12
743** %M minute 00-59
744** %s seconds since 1970-01-01
745** %S seconds 00-59
746** %w day of week 0-6 sunday==0
747** %W week of year 00-53
748** %Y year 0000-9999
749** %% %
750*/
drhf9b596e2004-05-26 16:54:42 +0000751static void strftimeFunc(
752 sqlite3_context *context,
753 int argc,
754 sqlite3_value **argv
755){
drh7014aff2003-11-01 01:53:53 +0000756 DateTime x;
757 int n, i, j;
758 char *z;
drh2646da72005-12-09 20:02:05 +0000759 const char *zFmt = (const char*)sqlite3_value_text(argv[0]);
drh7014aff2003-11-01 01:53:53 +0000760 char zBuf[100];
danielk197751ad0ec2004-05-24 12:39:02 +0000761 if( zFmt==0 || isDate(argc-1, argv+1, &x) ) return;
drh7014aff2003-11-01 01:53:53 +0000762 for(i=0, n=1; zFmt[i]; i++, n++){
763 if( zFmt[i]=='%' ){
764 switch( zFmt[i+1] ){
765 case 'd':
766 case 'H':
767 case 'm':
768 case 'M':
769 case 'S':
770 case 'W':
771 n++;
772 /* fall thru */
773 case 'w':
774 case '%':
775 break;
776 case 'f':
777 n += 8;
778 break;
779 case 'j':
780 n += 3;
781 break;
782 case 'Y':
783 n += 8;
784 break;
785 case 's':
786 case 'J':
787 n += 50;
788 break;
789 default:
790 return; /* ERROR. return a NULL */
791 }
792 i++;
793 }
794 }
795 if( n<sizeof(zBuf) ){
796 z = zBuf;
797 }else{
798 z = sqliteMalloc( n );
799 if( z==0 ) return;
800 }
801 computeJD(&x);
drhba212562004-01-08 02:17:31 +0000802 computeYMD_HMS(&x);
drh7014aff2003-11-01 01:53:53 +0000803 for(i=j=0; zFmt[i]; i++){
804 if( zFmt[i]!='%' ){
805 z[j++] = zFmt[i];
806 }else{
807 i++;
808 switch( zFmt[i] ){
809 case 'd': sprintf(&z[j],"%02d",x.D); j+=2; break;
810 case 'f': {
811 int s = x.s;
812 int ms = (x.s - s)*1000.0;
813 sprintf(&z[j],"%02d.%03d",s,ms);
814 j += strlen(&z[j]);
815 break;
816 }
817 case 'H': sprintf(&z[j],"%02d",x.h); j+=2; break;
818 case 'W': /* Fall thru */
819 case 'j': {
drh1020d492004-07-18 22:22:43 +0000820 int n; /* Number of days since 1st day of year */
drh7014aff2003-11-01 01:53:53 +0000821 DateTime y = x;
822 y.validJD = 0;
823 y.M = 1;
824 y.D = 1;
825 computeJD(&y);
drh1020d492004-07-18 22:22:43 +0000826 n = x.rJD - y.rJD;
drh7014aff2003-11-01 01:53:53 +0000827 if( zFmt[i]=='W' ){
drh1020d492004-07-18 22:22:43 +0000828 int wd; /* 0=Monday, 1=Tuesday, ... 6=Sunday */
829 wd = ((int)(x.rJD+0.5)) % 7;
830 sprintf(&z[j],"%02d",(n+7-wd)/7);
drh7014aff2003-11-01 01:53:53 +0000831 j += 2;
832 }else{
drh1020d492004-07-18 22:22:43 +0000833 sprintf(&z[j],"%03d",n+1);
drh7014aff2003-11-01 01:53:53 +0000834 j += 3;
835 }
836 break;
837 }
838 case 'J': sprintf(&z[j],"%.16g",x.rJD); j+=strlen(&z[j]); break;
839 case 'm': sprintf(&z[j],"%02d",x.M); j+=2; break;
840 case 'M': sprintf(&z[j],"%02d",x.m); j+=2; break;
841 case 's': {
drhc5dd9fa2004-01-07 03:29:16 +0000842 sprintf(&z[j],"%d",(int)((x.rJD-2440587.5)*86400.0 + 0.5));
drh7014aff2003-11-01 01:53:53 +0000843 j += strlen(&z[j]);
844 break;
845 }
drhc5dd9fa2004-01-07 03:29:16 +0000846 case 'S': sprintf(&z[j],"%02d",(int)(x.s+0.5)); j+=2; break;
drh7014aff2003-11-01 01:53:53 +0000847 case 'w': z[j++] = (((int)(x.rJD+1.5)) % 7) + '0'; break;
848 case 'Y': sprintf(&z[j],"%04d",x.Y); j+=strlen(&z[j]); break;
849 case '%': z[j++] = '%'; break;
850 }
851 }
852 }
853 z[j] = 0;
danielk1977d8123362004-06-12 09:25:12 +0000854 sqlite3_result_text(context, z, -1, SQLITE_TRANSIENT);
drh7014aff2003-11-01 01:53:53 +0000855 if( z!=zBuf ){
856 sqliteFree(z);
857 }
858}
859
danielk19777977a172004-11-09 12:44:37 +0000860/*
861** current_time()
862**
863** This function returns the same value as time('now').
864*/
865static void ctimeFunc(
866 sqlite3_context *context,
867 int argc,
868 sqlite3_value **argv
869){
870 sqlite3_value *pVal = sqlite3ValueNew();
871 if( pVal ){
872 sqlite3ValueSetStr(pVal, -1, "now", SQLITE_UTF8, SQLITE_STATIC);
873 timeFunc(context, 1, &pVal);
874 sqlite3ValueFree(pVal);
875 }
876}
drh7014aff2003-11-01 01:53:53 +0000877
danielk19777977a172004-11-09 12:44:37 +0000878/*
879** current_date()
880**
881** This function returns the same value as date('now').
882*/
883static void cdateFunc(
884 sqlite3_context *context,
885 int argc,
886 sqlite3_value **argv
887){
888 sqlite3_value *pVal = sqlite3ValueNew();
889 if( pVal ){
890 sqlite3ValueSetStr(pVal, -1, "now", SQLITE_UTF8, SQLITE_STATIC);
891 dateFunc(context, 1, &pVal);
892 sqlite3ValueFree(pVal);
893 }
894}
895
896/*
897** current_timestamp()
898**
899** This function returns the same value as datetime('now').
900*/
901static void ctimestampFunc(
902 sqlite3_context *context,
903 int argc,
904 sqlite3_value **argv
905){
906 sqlite3_value *pVal = sqlite3ValueNew();
907 if( pVal ){
908 sqlite3ValueSetStr(pVal, -1, "now", SQLITE_UTF8, SQLITE_STATIC);
909 datetimeFunc(context, 1, &pVal);
910 sqlite3ValueFree(pVal);
911 }
912}
drh7014aff2003-11-01 01:53:53 +0000913#endif /* !defined(SQLITE_OMIT_DATETIME_FUNCS) */
914
danielk1977752e6792004-11-09 16:13:33 +0000915#ifdef SQLITE_OMIT_DATETIME_FUNCS
916/*
917** If the library is compiled to omit the full-scale date and time
918** handling (to get a smaller binary), the following minimal version
919** of the functions current_time(), current_date() and current_timestamp()
920** are included instead. This is to support column declarations that
921** include "DEFAULT CURRENT_TIME" etc.
922**
danielk19772df9fab2004-11-11 01:50:30 +0000923** This function uses the C-library functions time(), gmtime()
danielk1977752e6792004-11-09 16:13:33 +0000924** and strftime(). The format string to pass to strftime() is supplied
925** as the user-data for the function.
926*/
danielk1977752e6792004-11-09 16:13:33 +0000927static void currentTimeFunc(
928 sqlite3_context *context,
929 int argc,
930 sqlite3_value **argv
931){
932 time_t t;
933 char *zFormat = (char *)sqlite3_user_data(context);
934 char zBuf[20];
danielk1977752e6792004-11-09 16:13:33 +0000935
danielk1977752e6792004-11-09 16:13:33 +0000936 time(&t);
937#ifdef SQLITE_TEST
drh6c626082004-11-14 21:56:29 +0000938 {
939 extern int sqlite3_current_time; /* See os_XXX.c */
940 if( sqlite3_current_time ){
941 t = sqlite3_current_time;
942 }
danielk1977752e6792004-11-09 16:13:33 +0000943 }
944#endif
danielk1977e6efa742004-11-10 11:55:10 +0000945
drh66560ad2006-01-06 14:32:19 +0000946 sqlite3OsEnterMutex();
danielk1977e6efa742004-11-10 11:55:10 +0000947 strftime(zBuf, 20, zFormat, gmtime(&t));
drh66560ad2006-01-06 14:32:19 +0000948 sqlite3OsLeaveMutex();
danielk1977e6efa742004-11-10 11:55:10 +0000949
danielk1977752e6792004-11-09 16:13:33 +0000950 sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
951}
952#endif
953
drh7014aff2003-11-01 01:53:53 +0000954/*
955** This function registered all of the above C functions as SQL
956** functions. This should be the only routine in this file with
957** external linkage.
958*/
drh9bb575f2004-09-06 17:24:11 +0000959void sqlite3RegisterDateTimeFunctions(sqlite3 *db){
drhfd1f3942004-07-20 00:39:14 +0000960#ifndef SQLITE_OMIT_DATETIME_FUNCS
drh57196282004-10-06 15:41:16 +0000961 static const struct {
drh7014aff2003-11-01 01:53:53 +0000962 char *zName;
963 int nArg;
danielk19770ae8b832004-05-25 12:05:56 +0000964 void (*xFunc)(sqlite3_context*,int,sqlite3_value**);
drh7014aff2003-11-01 01:53:53 +0000965 } aFuncs[] = {
drhf9b596e2004-05-26 16:54:42 +0000966 { "julianday", -1, juliandayFunc },
967 { "date", -1, dateFunc },
968 { "time", -1, timeFunc },
969 { "datetime", -1, datetimeFunc },
970 { "strftime", -1, strftimeFunc },
danielk19777977a172004-11-09 12:44:37 +0000971 { "current_time", 0, ctimeFunc },
972 { "current_timestamp", 0, ctimestampFunc },
973 { "current_date", 0, cdateFunc },
drh7014aff2003-11-01 01:53:53 +0000974 };
975 int i;
976
977 for(i=0; i<sizeof(aFuncs)/sizeof(aFuncs[0]); i++){
danielk1977d8123362004-06-12 09:25:12 +0000978 sqlite3_create_function(db, aFuncs[i].zName, aFuncs[i].nArg,
danielk1977f9d64d22004-06-19 08:18:07 +0000979 SQLITE_UTF8, 0, aFuncs[i].xFunc, 0, 0);
drh7014aff2003-11-01 01:53:53 +0000980 }
danielk1977752e6792004-11-09 16:13:33 +0000981#else
982 static const struct {
983 char *zName;
984 char *zFormat;
985 } aFuncs[] = {
986 { "current_time", "%H:%M:%S" },
987 { "current_date", "%Y-%m-%d" },
988 { "current_timestamp", "%Y-%m-%d %H:%M:%S" }
989 };
990 int i;
991
992 for(i=0; i<sizeof(aFuncs)/sizeof(aFuncs[0]); i++){
993 sqlite3_create_function(db, aFuncs[i].zName, 0, SQLITE_UTF8,
994 aFuncs[i].zFormat, currentTimeFunc, 0, 0);
995 }
drhfd1f3942004-07-20 00:39:14 +0000996#endif
drh7014aff2003-11-01 01:53:53 +0000997}