blob: 610ed9ef5521d35d7d526099d87103d6345dc1f8 [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**
drh1cfdc902008-02-21 20:40:43 +000019** $Id: date.c,v 1.76 2008/02/21 20:40:44 drh Exp $
drh7014aff2003-11-01 01:53:53 +000020**
21** SQLite processes all times and dates as Julian Day numbers. The
22** dates and times are stored as the number of days since noon
23** in Greenwich on November 24, 4714 B.C. according to the Gregorian
drh7f986a62006-09-25 18:05:04 +000024** calendar system.
drh7014aff2003-11-01 01:53:53 +000025**
26** 1970-01-01 00:00:00 is JD 2440587.5
27** 2000-01-01 00:00:00 is JD 2451544.5
28**
29** This implemention requires years to be expressed as a 4-digit number
30** which means that only dates between 0000-01-01 and 9999-12-31 can
31** be represented, even though julian day numbers allow a much wider
32** range of dates.
33**
34** The Gregorian calendar system is used for all dates and times,
35** even those that predate the Gregorian calendar. Historians usually
36** use the Julian calendar for dates prior to 1582-10-15 and for some
37** dates afterwards, depending on locale. Beware of this difference.
38**
39** The conversion algorithms are implemented based on descriptions
40** in the following text:
41**
42** Jean Meeus
43** Astronomical Algorithms, 2nd Edition, 1998
44** ISBM 0-943396-61-1
45** Willmann-Bell, Inc
46** Richmond, Virginia (USA)
47*/
dougcurrieae534182003-12-24 01:41:19 +000048#include "sqliteInt.h"
drh7014aff2003-11-01 01:53:53 +000049#include <ctype.h>
50#include <stdlib.h>
51#include <assert.h>
drh7091cb02003-12-23 16:22:18 +000052#include <time.h>
drh7014aff2003-11-01 01:53:53 +000053
drh4bc05852004-02-10 13:19:35 +000054#ifndef SQLITE_OMIT_DATETIME_FUNCS
55
drh7014aff2003-11-01 01:53:53 +000056/*
57** A structure for holding a single date and time.
58*/
59typedef struct DateTime DateTime;
60struct DateTime {
61 double rJD; /* The julian day number */
62 int Y, M, D; /* Year, month, and day */
63 int h, m; /* Hour and minutes */
64 int tz; /* Timezone offset in minutes */
65 double s; /* Seconds */
66 char validYMD; /* True if Y,M,D are valid */
67 char validHMS; /* True if h,m,s are valid */
68 char validJD; /* True if rJD is valid */
69 char validTZ; /* True if tz is valid */
70};
71
72
73/*
drheb9a9e82004-02-22 17:49:32 +000074** Convert zDate into one or more integers. Additional arguments
75** come in groups of 5 as follows:
76**
77** N number of digits in the integer
78** min minimum allowed value of the integer
79** max maximum allowed value of the integer
80** nextC first character after the integer
81** pVal where to write the integers value.
82**
83** Conversions continue until one with nextC==0 is encountered.
84** The function returns the number of successful conversions.
drh7014aff2003-11-01 01:53:53 +000085*/
drheb9a9e82004-02-22 17:49:32 +000086static int getDigits(const char *zDate, ...){
87 va_list ap;
88 int val;
89 int N;
90 int min;
91 int max;
92 int nextC;
93 int *pVal;
94 int cnt = 0;
95 va_start(ap, zDate);
96 do{
97 N = va_arg(ap, int);
98 min = va_arg(ap, int);
99 max = va_arg(ap, int);
100 nextC = va_arg(ap, int);
101 pVal = va_arg(ap, int*);
102 val = 0;
103 while( N-- ){
drh4c755c02004-08-08 20:22:17 +0000104 if( !isdigit(*(u8*)zDate) ){
drh029b44b2006-01-15 00:13:15 +0000105 goto end_getDigits;
drheb9a9e82004-02-22 17:49:32 +0000106 }
107 val = val*10 + *zDate - '0';
108 zDate++;
109 }
110 if( val<min || val>max || (nextC!=0 && nextC!=*zDate) ){
drh029b44b2006-01-15 00:13:15 +0000111 goto end_getDigits;
drheb9a9e82004-02-22 17:49:32 +0000112 }
113 *pVal = val;
drh7014aff2003-11-01 01:53:53 +0000114 zDate++;
drheb9a9e82004-02-22 17:49:32 +0000115 cnt++;
116 }while( nextC );
drh029b44b2006-01-15 00:13:15 +0000117end_getDigits:
drh15b9a152006-01-31 20:49:13 +0000118 va_end(ap);
drheb9a9e82004-02-22 17:49:32 +0000119 return cnt;
drh7014aff2003-11-01 01:53:53 +0000120}
121
122/*
123** Read text from z[] and convert into a floating point number. Return
124** the number of digits converted.
125*/
drh487e2622005-06-25 18:42:14 +0000126#define getValue sqlite3AtoF
drh7014aff2003-11-01 01:53:53 +0000127
128/*
129** Parse a timezone extension on the end of a date-time.
130** The extension is of the form:
131**
132** (+/-)HH:MM
133**
drh1cfdc902008-02-21 20:40:43 +0000134** Or the "zulu" notation:
135**
136** Z
137**
drh7014aff2003-11-01 01:53:53 +0000138** If the parse is successful, write the number of minutes
drh1cfdc902008-02-21 20:40:43 +0000139** of change in p->tz and return 0. If a parser error occurs,
140** return non-zero.
drh7014aff2003-11-01 01:53:53 +0000141**
142** A missing specifier is not considered an error.
143*/
144static int parseTimezone(const char *zDate, DateTime *p){
145 int sgn = 0;
146 int nHr, nMn;
drh1cfdc902008-02-21 20:40:43 +0000147 int c;
drh4c755c02004-08-08 20:22:17 +0000148 while( isspace(*(u8*)zDate) ){ zDate++; }
drh7014aff2003-11-01 01:53:53 +0000149 p->tz = 0;
drh1cfdc902008-02-21 20:40:43 +0000150 c = *zDate;
151 if( c=='-' ){
drh7014aff2003-11-01 01:53:53 +0000152 sgn = -1;
drh1cfdc902008-02-21 20:40:43 +0000153 }else if( c=='+' ){
drh7014aff2003-11-01 01:53:53 +0000154 sgn = +1;
drh1cfdc902008-02-21 20:40:43 +0000155 }else if( c=='Z' || c=='z' ){
156 zDate++;
157 goto zulu_time;
drh7014aff2003-11-01 01:53:53 +0000158 }else{
drh1cfdc902008-02-21 20:40:43 +0000159 return c!=0;
drh7014aff2003-11-01 01:53:53 +0000160 }
161 zDate++;
drheb9a9e82004-02-22 17:49:32 +0000162 if( getDigits(zDate, 2, 0, 14, ':', &nHr, 2, 0, 59, 0, &nMn)!=2 ){
163 return 1;
164 }
165 zDate += 5;
drh7014aff2003-11-01 01:53:53 +0000166 p->tz = sgn*(nMn + nHr*60);
drh1cfdc902008-02-21 20:40:43 +0000167zulu_time:
drh4c755c02004-08-08 20:22:17 +0000168 while( isspace(*(u8*)zDate) ){ zDate++; }
drh7014aff2003-11-01 01:53:53 +0000169 return *zDate!=0;
170}
171
172/*
173** Parse times of the form HH:MM or HH:MM:SS or HH:MM:SS.FFFF.
174** The HH, MM, and SS must each be exactly 2 digits. The
175** fractional seconds FFFF can be one or more digits.
176**
177** Return 1 if there is a parsing error and 0 on success.
178*/
179static int parseHhMmSs(const char *zDate, DateTime *p){
180 int h, m, s;
181 double ms = 0.0;
drheb9a9e82004-02-22 17:49:32 +0000182 if( getDigits(zDate, 2, 0, 24, ':', &h, 2, 0, 59, 0, &m)!=2 ){
183 return 1;
184 }
185 zDate += 5;
drh7014aff2003-11-01 01:53:53 +0000186 if( *zDate==':' ){
drheb9a9e82004-02-22 17:49:32 +0000187 zDate++;
188 if( getDigits(zDate, 2, 0, 59, 0, &s)!=1 ){
189 return 1;
190 }
191 zDate += 2;
drh4c755c02004-08-08 20:22:17 +0000192 if( *zDate=='.' && isdigit((u8)zDate[1]) ){
drh7014aff2003-11-01 01:53:53 +0000193 double rScale = 1.0;
194 zDate++;
drh4c755c02004-08-08 20:22:17 +0000195 while( isdigit(*(u8*)zDate) ){
drh7014aff2003-11-01 01:53:53 +0000196 ms = ms*10.0 + *zDate - '0';
197 rScale *= 10.0;
198 zDate++;
199 }
200 ms /= rScale;
201 }
202 }else{
203 s = 0;
204 }
205 p->validJD = 0;
206 p->validHMS = 1;
207 p->h = h;
208 p->m = m;
209 p->s = s + ms;
210 if( parseTimezone(zDate, p) ) return 1;
211 p->validTZ = p->tz!=0;
212 return 0;
213}
214
215/*
216** Convert from YYYY-MM-DD HH:MM:SS to julian day. We always assume
217** that the YYYY-MM-DD is according to the Gregorian calendar.
218**
219** Reference: Meeus page 61
220*/
221static void computeJD(DateTime *p){
222 int Y, M, D, A, B, X1, X2;
223
224 if( p->validJD ) return;
225 if( p->validYMD ){
226 Y = p->Y;
227 M = p->M;
228 D = p->D;
229 }else{
drhba212562004-01-08 02:17:31 +0000230 Y = 2000; /* If no YMD specified, assume 2000-Jan-01 */
drh7014aff2003-11-01 01:53:53 +0000231 M = 1;
232 D = 1;
233 }
234 if( M<=2 ){
235 Y--;
236 M += 12;
237 }
238 A = Y/100;
239 B = 2 - A + (A/4);
240 X1 = 365.25*(Y+4716);
241 X2 = 30.6001*(M+1);
242 p->rJD = X1 + X2 + D + B - 1524.5;
243 p->validJD = 1;
drh7014aff2003-11-01 01:53:53 +0000244 if( p->validHMS ){
245 p->rJD += (p->h*3600.0 + p->m*60.0 + p->s)/86400.0;
246 if( p->validTZ ){
drh57391032006-01-09 00:18:02 +0000247 p->rJD -= p->tz*60/86400.0;
drhf11c34d2006-09-08 12:27:36 +0000248 p->validYMD = 0;
drh7014aff2003-11-01 01:53:53 +0000249 p->validHMS = 0;
250 p->validTZ = 0;
251 }
252 }
253}
254
255/*
256** Parse dates of the form
257**
258** YYYY-MM-DD HH:MM:SS.FFF
259** YYYY-MM-DD HH:MM:SS
260** YYYY-MM-DD HH:MM
261** YYYY-MM-DD
262**
263** Write the result into the DateTime structure and return 0
264** on success and 1 if the input string is not a well-formed
265** date.
266*/
267static int parseYyyyMmDd(const char *zDate, DateTime *p){
drh8eb2cce2004-02-21 03:28:18 +0000268 int Y, M, D, neg;
drh7014aff2003-11-01 01:53:53 +0000269
drh8eb2cce2004-02-21 03:28:18 +0000270 if( zDate[0]=='-' ){
271 zDate++;
272 neg = 1;
273 }else{
274 neg = 0;
275 }
drheb9a9e82004-02-22 17:49:32 +0000276 if( getDigits(zDate,4,0,9999,'-',&Y,2,1,12,'-',&M,2,1,31,0,&D)!=3 ){
277 return 1;
278 }
279 zDate += 10;
drh4cb29b42005-03-21 00:43:44 +0000280 while( isspace(*(u8*)zDate) || 'T'==*(u8*)zDate ){ zDate++; }
drheb9a9e82004-02-22 17:49:32 +0000281 if( parseHhMmSs(zDate, p)==0 ){
282 /* We got the time */
drh7014aff2003-11-01 01:53:53 +0000283 }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*/
danielk1977fee2d252007-08-18 10:59:19 +0000315static int parseDateOrTime(
316 sqlite3_context *context,
317 const char *zDate,
318 DateTime *p
319){
drh7014aff2003-11-01 01:53:53 +0000320 memset(p, 0, sizeof(*p));
drh8eb2cce2004-02-21 03:28:18 +0000321 if( parseYyyyMmDd(zDate,p)==0 ){
drh7014aff2003-11-01 01:53:53 +0000322 return 0;
drh8eb2cce2004-02-21 03:28:18 +0000323 }else if( parseHhMmSs(zDate, p)==0 ){
324 return 0;
danielk19774adee202004-05-08 08:23:19 +0000325 }else if( sqlite3StrICmp(zDate,"now")==0){
drh7014aff2003-11-01 01:53:53 +0000326 double r;
danielk1977fee2d252007-08-18 10:59:19 +0000327 sqlite3OsCurrentTime((sqlite3_vfs *)sqlite3_user_data(context), &r);
drh018d1a42005-01-15 01:52:31 +0000328 p->rJD = r;
329 p->validJD = 1;
330 return 0;
danielk1977dc8453f2004-06-12 00:42:34 +0000331 }else if( sqlite3IsNumber(zDate, 0, SQLITE_UTF8) ){
drh487e2622005-06-25 18:42:14 +0000332 getValue(zDate, &p->rJD);
drh7014aff2003-11-01 01:53:53 +0000333 p->validJD = 1;
334 return 0;
335 }
336 return 1;
337}
338
339/*
340** Compute the Year, Month, and Day from the julian day number.
341*/
342static void computeYMD(DateTime *p){
343 int Z, A, B, C, D, E, X1;
344 if( p->validYMD ) return;
drh33a9ad22004-02-29 00:40:32 +0000345 if( !p->validJD ){
346 p->Y = 2000;
347 p->M = 1;
348 p->D = 1;
349 }else{
350 Z = p->rJD + 0.5;
351 A = (Z - 1867216.25)/36524.25;
352 A = Z + 1 + A - (A/4);
353 B = A + 1524;
354 C = (B - 122.1)/365.25;
355 D = 365.25*C;
356 E = (B-D)/30.6001;
357 X1 = 30.6001*E;
358 p->D = B - D - X1;
359 p->M = E<14 ? E-1 : E-13;
360 p->Y = p->M>2 ? C - 4716 : C - 4715;
361 }
drh7014aff2003-11-01 01:53:53 +0000362 p->validYMD = 1;
363}
364
365/*
366** Compute the Hour, Minute, and Seconds from the julian day number.
367*/
368static void computeHMS(DateTime *p){
369 int Z, s;
370 if( p->validHMS ) return;
drhf11c34d2006-09-08 12:27:36 +0000371 computeJD(p);
drh7014aff2003-11-01 01:53:53 +0000372 Z = p->rJD + 0.5;
373 s = (p->rJD + 0.5 - Z)*86400000.0 + 0.5;
374 p->s = 0.001*s;
375 s = p->s;
376 p->s -= s;
377 p->h = s/3600;
378 s -= p->h*3600;
379 p->m = s/60;
380 p->s += s - p->m*60;
381 p->validHMS = 1;
382}
383
384/*
drhba212562004-01-08 02:17:31 +0000385** Compute both YMD and HMS
386*/
387static void computeYMD_HMS(DateTime *p){
388 computeYMD(p);
389 computeHMS(p);
390}
391
392/*
393** Clear the YMD and HMS and the TZ
394*/
395static void clearYMD_HMS_TZ(DateTime *p){
396 p->validYMD = 0;
397 p->validHMS = 0;
398 p->validTZ = 0;
399}
400
401/*
drh7091cb02003-12-23 16:22:18 +0000402** Compute the difference (in days) between localtime and UTC (a.k.a. GMT)
403** for the time value p where p is in UTC.
404*/
405static double localtimeOffset(DateTime *p){
406 DateTime x, y;
407 time_t t;
drh7091cb02003-12-23 16:22:18 +0000408 x = *p;
drhba212562004-01-08 02:17:31 +0000409 computeYMD_HMS(&x);
drh7091cb02003-12-23 16:22:18 +0000410 if( x.Y<1971 || x.Y>=2038 ){
411 x.Y = 2000;
412 x.M = 1;
413 x.D = 1;
414 x.h = 0;
415 x.m = 0;
416 x.s = 0.0;
417 } else {
418 int s = x.s + 0.5;
419 x.s = s;
420 }
421 x.tz = 0;
422 x.validJD = 0;
423 computeJD(&x);
424 t = (x.rJD-2440587.5)*86400.0 + 0.5;
drh87595762006-09-08 12:49:43 +0000425#ifdef HAVE_LOCALTIME_R
426 {
427 struct tm sLocal;
428 localtime_r(&t, &sLocal);
429 y.Y = sLocal.tm_year + 1900;
430 y.M = sLocal.tm_mon + 1;
431 y.D = sLocal.tm_mday;
432 y.h = sLocal.tm_hour;
433 y.m = sLocal.tm_min;
434 y.s = sLocal.tm_sec;
435 }
436#else
437 {
438 struct tm *pTm;
drh153c62c2007-08-24 03:51:33 +0000439 sqlite3_mutex_enter(sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_MASTER));
drh87595762006-09-08 12:49:43 +0000440 pTm = localtime(&t);
441 y.Y = pTm->tm_year + 1900;
442 y.M = pTm->tm_mon + 1;
443 y.D = pTm->tm_mday;
444 y.h = pTm->tm_hour;
445 y.m = pTm->tm_min;
446 y.s = pTm->tm_sec;
drh153c62c2007-08-24 03:51:33 +0000447 sqlite3_mutex_leave(sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_MASTER));
drh87595762006-09-08 12:49:43 +0000448 }
449#endif
drh7091cb02003-12-23 16:22:18 +0000450 y.validYMD = 1;
451 y.validHMS = 1;
452 y.validJD = 0;
453 y.validTZ = 0;
454 computeJD(&y);
drh7091cb02003-12-23 16:22:18 +0000455 return y.rJD - x.rJD;
456}
457
458/*
drh7014aff2003-11-01 01:53:53 +0000459** Process a modifier to a date-time stamp. The modifiers are
460** as follows:
461**
462** NNN days
463** NNN hours
464** NNN minutes
465** NNN.NNNN seconds
466** NNN months
467** NNN years
468** start of month
469** start of year
470** start of week
471** start of day
472** weekday N
473** unixepoch
drh7091cb02003-12-23 16:22:18 +0000474** localtime
475** utc
drh7014aff2003-11-01 01:53:53 +0000476**
477** Return 0 on success and 1 if there is any kind of error.
478*/
479static int parseModifier(const char *zMod, DateTime *p){
480 int rc = 1;
481 int n;
482 double r;
drh4d5b8362004-01-17 01:16:21 +0000483 char *z, zBuf[30];
484 z = zBuf;
485 for(n=0; n<sizeof(zBuf)-1 && zMod[n]; n++){
drh7014aff2003-11-01 01:53:53 +0000486 z[n] = tolower(zMod[n]);
487 }
488 z[n] = 0;
489 switch( z[0] ){
drh7091cb02003-12-23 16:22:18 +0000490 case 'l': {
491 /* localtime
492 **
493 ** Assuming the current time value is UTC (a.k.a. GMT), shift it to
494 ** show local time.
495 */
496 if( strcmp(z, "localtime")==0 ){
497 computeJD(p);
498 p->rJD += localtimeOffset(p);
drhba212562004-01-08 02:17:31 +0000499 clearYMD_HMS_TZ(p);
drh7091cb02003-12-23 16:22:18 +0000500 rc = 0;
501 }
502 break;
503 }
drh7014aff2003-11-01 01:53:53 +0000504 case 'u': {
505 /*
506 ** unixepoch
507 **
508 ** Treat the current value of p->rJD as the number of
509 ** seconds since 1970. Convert to a real julian day number.
510 */
511 if( strcmp(z, "unixepoch")==0 && p->validJD ){
512 p->rJD = p->rJD/86400.0 + 2440587.5;
drhba212562004-01-08 02:17:31 +0000513 clearYMD_HMS_TZ(p);
drh7014aff2003-11-01 01:53:53 +0000514 rc = 0;
drh7091cb02003-12-23 16:22:18 +0000515 }else if( strcmp(z, "utc")==0 ){
516 double c1;
517 computeJD(p);
518 c1 = localtimeOffset(p);
519 p->rJD -= c1;
drhba212562004-01-08 02:17:31 +0000520 clearYMD_HMS_TZ(p);
drh7091cb02003-12-23 16:22:18 +0000521 p->rJD += c1 - localtimeOffset(p);
drh7091cb02003-12-23 16:22:18 +0000522 rc = 0;
drh7014aff2003-11-01 01:53:53 +0000523 }
524 break;
525 }
526 case 'w': {
527 /*
528 ** weekday N
529 **
drh181fc992004-08-17 10:42:54 +0000530 ** Move the date to the same time on the next occurrence of
drh7014aff2003-11-01 01:53:53 +0000531 ** weekday N where 0==Sunday, 1==Monday, and so forth. If the
drhc5dd9fa2004-01-07 03:29:16 +0000532 ** date is already on the appropriate weekday, this is a no-op.
drh7014aff2003-11-01 01:53:53 +0000533 */
534 if( strncmp(z, "weekday ", 8)==0 && getValue(&z[8],&r)>0
535 && (n=r)==r && n>=0 && r<7 ){
536 int Z;
drhba212562004-01-08 02:17:31 +0000537 computeYMD_HMS(p);
drh7014aff2003-11-01 01:53:53 +0000538 p->validTZ = 0;
539 p->validJD = 0;
540 computeJD(p);
541 Z = p->rJD + 1.5;
542 Z %= 7;
543 if( Z>n ) Z -= 7;
544 p->rJD += n - Z;
drhba212562004-01-08 02:17:31 +0000545 clearYMD_HMS_TZ(p);
drh7014aff2003-11-01 01:53:53 +0000546 rc = 0;
547 }
548 break;
549 }
550 case 's': {
551 /*
552 ** start of TTTTT
553 **
554 ** Move the date backwards to the beginning of the current day,
555 ** or month or year.
556 */
557 if( strncmp(z, "start of ", 9)!=0 ) break;
drh4d5b8362004-01-17 01:16:21 +0000558 z += 9;
drh7014aff2003-11-01 01:53:53 +0000559 computeYMD(p);
560 p->validHMS = 1;
561 p->h = p->m = 0;
562 p->s = 0.0;
563 p->validTZ = 0;
564 p->validJD = 0;
drh4d5b8362004-01-17 01:16:21 +0000565 if( strcmp(z,"month")==0 ){
drh7014aff2003-11-01 01:53:53 +0000566 p->D = 1;
567 rc = 0;
drh4d5b8362004-01-17 01:16:21 +0000568 }else if( strcmp(z,"year")==0 ){
drh7014aff2003-11-01 01:53:53 +0000569 computeYMD(p);
570 p->M = 1;
571 p->D = 1;
572 rc = 0;
drh4d5b8362004-01-17 01:16:21 +0000573 }else if( strcmp(z,"day")==0 ){
drh7014aff2003-11-01 01:53:53 +0000574 rc = 0;
575 }
576 break;
577 }
578 case '+':
579 case '-':
580 case '0':
581 case '1':
582 case '2':
583 case '3':
584 case '4':
585 case '5':
586 case '6':
587 case '7':
588 case '8':
589 case '9': {
590 n = getValue(z, &r);
drh05f7c192007-04-06 02:32:33 +0000591 assert( n>=1 );
drh33a9ad22004-02-29 00:40:32 +0000592 if( z[n]==':' ){
593 /* A modifier of the form (+|-)HH:MM:SS.FFF adds (or subtracts) the
594 ** specified number of hours, minutes, seconds, and fractional seconds
595 ** to the time. The ".FFF" may be omitted. The ":SS.FFF" may be
596 ** omitted.
597 */
598 const char *z2 = z;
599 DateTime tx;
600 int day;
drh4c755c02004-08-08 20:22:17 +0000601 if( !isdigit(*(u8*)z2) ) z2++;
drh33a9ad22004-02-29 00:40:32 +0000602 memset(&tx, 0, sizeof(tx));
603 if( parseHhMmSs(z2, &tx) ) break;
604 computeJD(&tx);
drh0d131ab2004-02-29 01:08:17 +0000605 tx.rJD -= 0.5;
drh33a9ad22004-02-29 00:40:32 +0000606 day = (int)tx.rJD;
drhb6829e92004-02-29 00:50:33 +0000607 tx.rJD -= day;
drhb6829e92004-02-29 00:50:33 +0000608 if( z[0]=='-' ) tx.rJD = -tx.rJD;
drh0d131ab2004-02-29 01:08:17 +0000609 computeJD(p);
610 clearYMD_HMS_TZ(p);
drhf11c34d2006-09-08 12:27:36 +0000611 p->rJD += tx.rJD;
drh33a9ad22004-02-29 00:40:32 +0000612 rc = 0;
613 break;
614 }
drh4d5b8362004-01-17 01:16:21 +0000615 z += n;
drh4c755c02004-08-08 20:22:17 +0000616 while( isspace(*(u8*)z) ) z++;
drh4d5b8362004-01-17 01:16:21 +0000617 n = strlen(z);
drh7014aff2003-11-01 01:53:53 +0000618 if( n>10 || n<3 ) break;
drh7014aff2003-11-01 01:53:53 +0000619 if( z[n-1]=='s' ){ z[n-1] = 0; n--; }
620 computeJD(p);
621 rc = 0;
622 if( n==3 && strcmp(z,"day")==0 ){
623 p->rJD += r;
624 }else if( n==4 && strcmp(z,"hour")==0 ){
drh7014aff2003-11-01 01:53:53 +0000625 p->rJD += r/24.0;
626 }else if( n==6 && strcmp(z,"minute")==0 ){
drh7014aff2003-11-01 01:53:53 +0000627 p->rJD += r/(24.0*60.0);
628 }else if( n==6 && strcmp(z,"second")==0 ){
drh7014aff2003-11-01 01:53:53 +0000629 p->rJD += r/(24.0*60.0*60.0);
630 }else if( n==5 && strcmp(z,"month")==0 ){
631 int x, y;
drhba212562004-01-08 02:17:31 +0000632 computeYMD_HMS(p);
drh7014aff2003-11-01 01:53:53 +0000633 p->M += r;
634 x = p->M>0 ? (p->M-1)/12 : (p->M-12)/12;
635 p->Y += x;
636 p->M -= x*12;
637 p->validJD = 0;
638 computeJD(p);
639 y = r;
640 if( y!=r ){
641 p->rJD += (r - y)*30.0;
642 }
643 }else if( n==4 && strcmp(z,"year")==0 ){
drhba212562004-01-08 02:17:31 +0000644 computeYMD_HMS(p);
drh7014aff2003-11-01 01:53:53 +0000645 p->Y += r;
646 p->validJD = 0;
647 computeJD(p);
648 }else{
649 rc = 1;
650 }
drhba212562004-01-08 02:17:31 +0000651 clearYMD_HMS_TZ(p);
drh7014aff2003-11-01 01:53:53 +0000652 break;
653 }
654 default: {
655 break;
656 }
657 }
658 return rc;
659}
660
661/*
662** Process time function arguments. argv[0] is a date-time stamp.
663** argv[1] and following are modifiers. Parse them all and write
664** the resulting time into the DateTime structure p. Return 0
665** on success and 1 if there are any errors.
drh008e4762008-01-17 22:27:53 +0000666**
667** If there are zero parameters (if even argv[0] is undefined)
668** then assume a default value of "now" for argv[0].
drh7014aff2003-11-01 01:53:53 +0000669*/
danielk1977fee2d252007-08-18 10:59:19 +0000670static int isDate(
671 sqlite3_context *context,
672 int argc,
673 sqlite3_value **argv,
674 DateTime *p
675){
drh7014aff2003-11-01 01:53:53 +0000676 int i;
drh7a521cf2007-04-25 18:23:52 +0000677 const unsigned char *z;
drh008e4762008-01-17 22:27:53 +0000678 static const unsigned char zDflt[] = "now";
679 if( argc==0 ){
680 z = zDflt;
681 }else{
682 z = sqlite3_value_text(argv[0]);
683 }
danielk1977fee2d252007-08-18 10:59:19 +0000684 if( !z || parseDateOrTime(context, (char*)z, p) ){
drh7a521cf2007-04-25 18:23:52 +0000685 return 1;
686 }
drh7014aff2003-11-01 01:53:53 +0000687 for(i=1; i<argc; i++){
drh7a521cf2007-04-25 18:23:52 +0000688 if( (z = sqlite3_value_text(argv[i]))==0 || parseModifier((char*)z, p) ){
689 return 1;
690 }
drh7014aff2003-11-01 01:53:53 +0000691 }
692 return 0;
693}
694
695
696/*
697** The following routines implement the various date and time functions
698** of SQLite.
699*/
700
701/*
702** julianday( TIMESTRING, MOD, MOD, ...)
703**
704** Return the julian day number of the date specified in the arguments
705*/
drhf9b596e2004-05-26 16:54:42 +0000706static void juliandayFunc(
707 sqlite3_context *context,
708 int argc,
709 sqlite3_value **argv
710){
drh7014aff2003-11-01 01:53:53 +0000711 DateTime x;
danielk1977fee2d252007-08-18 10:59:19 +0000712 if( isDate(context, argc, argv, &x)==0 ){
drh7014aff2003-11-01 01:53:53 +0000713 computeJD(&x);
danielk19777e18c252004-05-25 11:47:24 +0000714 sqlite3_result_double(context, x.rJD);
drh7014aff2003-11-01 01:53:53 +0000715 }
716}
717
718/*
719** datetime( TIMESTRING, MOD, MOD, ...)
720**
721** Return YYYY-MM-DD HH:MM:SS
722*/
drhf9b596e2004-05-26 16:54:42 +0000723static void datetimeFunc(
724 sqlite3_context *context,
725 int argc,
726 sqlite3_value **argv
727){
drh7014aff2003-11-01 01:53:53 +0000728 DateTime x;
danielk1977fee2d252007-08-18 10:59:19 +0000729 if( isDate(context, argc, argv, &x)==0 ){
drh7014aff2003-11-01 01:53:53 +0000730 char zBuf[100];
drhba212562004-01-08 02:17:31 +0000731 computeYMD_HMS(&x);
drh5bb3eb92007-05-04 13:15:55 +0000732 sqlite3_snprintf(sizeof(zBuf), zBuf, "%04d-%02d-%02d %02d:%02d:%02d",
733 x.Y, x.M, x.D, x.h, x.m, (int)(x.s));
danielk1977d8123362004-06-12 09:25:12 +0000734 sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
drh7014aff2003-11-01 01:53:53 +0000735 }
736}
737
738/*
739** time( TIMESTRING, MOD, MOD, ...)
740**
741** Return HH:MM:SS
742*/
drhf9b596e2004-05-26 16:54:42 +0000743static void timeFunc(
744 sqlite3_context *context,
745 int argc,
746 sqlite3_value **argv
747){
drh7014aff2003-11-01 01:53:53 +0000748 DateTime x;
danielk1977fee2d252007-08-18 10:59:19 +0000749 if( isDate(context, argc, argv, &x)==0 ){
drh7014aff2003-11-01 01:53:53 +0000750 char zBuf[100];
751 computeHMS(&x);
drh5bb3eb92007-05-04 13:15:55 +0000752 sqlite3_snprintf(sizeof(zBuf), zBuf, "%02d:%02d:%02d", x.h, x.m, (int)x.s);
danielk1977d8123362004-06-12 09:25:12 +0000753 sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
drh7014aff2003-11-01 01:53:53 +0000754 }
755}
756
757/*
758** date( TIMESTRING, MOD, MOD, ...)
759**
760** Return YYYY-MM-DD
761*/
drhf9b596e2004-05-26 16:54:42 +0000762static void dateFunc(
763 sqlite3_context *context,
764 int argc,
765 sqlite3_value **argv
766){
drh7014aff2003-11-01 01:53:53 +0000767 DateTime x;
danielk1977fee2d252007-08-18 10:59:19 +0000768 if( isDate(context, argc, argv, &x)==0 ){
drh7014aff2003-11-01 01:53:53 +0000769 char zBuf[100];
770 computeYMD(&x);
drh5bb3eb92007-05-04 13:15:55 +0000771 sqlite3_snprintf(sizeof(zBuf), zBuf, "%04d-%02d-%02d", x.Y, x.M, x.D);
danielk1977d8123362004-06-12 09:25:12 +0000772 sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
drh7014aff2003-11-01 01:53:53 +0000773 }
774}
775
776/*
777** strftime( FORMAT, TIMESTRING, MOD, MOD, ...)
778**
779** Return a string described by FORMAT. Conversions as follows:
780**
781** %d day of month
782** %f ** fractional seconds SS.SSS
783** %H hour 00-24
784** %j day of year 000-366
785** %J ** Julian day number
786** %m month 01-12
787** %M minute 00-59
788** %s seconds since 1970-01-01
789** %S seconds 00-59
790** %w day of week 0-6 sunday==0
791** %W week of year 00-53
792** %Y year 0000-9999
793** %% %
794*/
drhf9b596e2004-05-26 16:54:42 +0000795static void strftimeFunc(
796 sqlite3_context *context,
797 int argc,
798 sqlite3_value **argv
799){
drh7014aff2003-11-01 01:53:53 +0000800 DateTime x;
drha0206bc2007-05-08 15:15:02 +0000801 u64 n;
802 int i, j;
drh7014aff2003-11-01 01:53:53 +0000803 char *z;
drh2646da72005-12-09 20:02:05 +0000804 const char *zFmt = (const char*)sqlite3_value_text(argv[0]);
drh7014aff2003-11-01 01:53:53 +0000805 char zBuf[100];
danielk1977fee2d252007-08-18 10:59:19 +0000806 if( zFmt==0 || isDate(context, argc-1, argv+1, &x) ) return;
drh7014aff2003-11-01 01:53:53 +0000807 for(i=0, n=1; zFmt[i]; i++, n++){
808 if( zFmt[i]=='%' ){
809 switch( zFmt[i+1] ){
810 case 'd':
811 case 'H':
812 case 'm':
813 case 'M':
814 case 'S':
815 case 'W':
816 n++;
817 /* fall thru */
818 case 'w':
819 case '%':
820 break;
821 case 'f':
822 n += 8;
823 break;
824 case 'j':
825 n += 3;
826 break;
827 case 'Y':
828 n += 8;
829 break;
830 case 's':
831 case 'J':
832 n += 50;
833 break;
834 default:
835 return; /* ERROR. return a NULL */
836 }
837 i++;
838 }
839 }
840 if( n<sizeof(zBuf) ){
841 z = zBuf;
drha0206bc2007-05-08 15:15:02 +0000842 }else if( n>SQLITE_MAX_LENGTH ){
843 sqlite3_result_error_toobig(context);
844 return;
drh7014aff2003-11-01 01:53:53 +0000845 }else{
drh17435752007-08-16 04:30:38 +0000846 z = sqlite3_malloc( n );
drh3334e942008-01-17 20:26:46 +0000847 if( z==0 ){
848 sqlite3_result_error_nomem(context);
849 return;
850 }
drh7014aff2003-11-01 01:53:53 +0000851 }
852 computeJD(&x);
drhba212562004-01-08 02:17:31 +0000853 computeYMD_HMS(&x);
drh7014aff2003-11-01 01:53:53 +0000854 for(i=j=0; zFmt[i]; i++){
855 if( zFmt[i]!='%' ){
856 z[j++] = zFmt[i];
857 }else{
858 i++;
859 switch( zFmt[i] ){
drh5bb3eb92007-05-04 13:15:55 +0000860 case 'd': sqlite3_snprintf(3, &z[j],"%02d",x.D); j+=2; break;
drh7014aff2003-11-01 01:53:53 +0000861 case 'f': {
drhb1f1e6e2006-09-25 18:01:31 +0000862 double s = x.s;
863 if( s>59.999 ) s = 59.999;
drh2ecad3b2007-03-29 17:57:21 +0000864 sqlite3_snprintf(7, &z[j],"%06.3f", s);
drh7014aff2003-11-01 01:53:53 +0000865 j += strlen(&z[j]);
866 break;
867 }
drh5bb3eb92007-05-04 13:15:55 +0000868 case 'H': sqlite3_snprintf(3, &z[j],"%02d",x.h); j+=2; break;
drh7014aff2003-11-01 01:53:53 +0000869 case 'W': /* Fall thru */
870 case 'j': {
danielk1977f0113002006-01-24 12:09:17 +0000871 int nDay; /* Number of days since 1st day of year */
drh7014aff2003-11-01 01:53:53 +0000872 DateTime y = x;
873 y.validJD = 0;
874 y.M = 1;
875 y.D = 1;
876 computeJD(&y);
drhc2c9eef2007-01-08 13:07:30 +0000877 nDay = x.rJD - y.rJD + 0.5;
drh7014aff2003-11-01 01:53:53 +0000878 if( zFmt[i]=='W' ){
drh1020d492004-07-18 22:22:43 +0000879 int wd; /* 0=Monday, 1=Tuesday, ... 6=Sunday */
880 wd = ((int)(x.rJD+0.5)) % 7;
drh5bb3eb92007-05-04 13:15:55 +0000881 sqlite3_snprintf(3, &z[j],"%02d",(nDay+7-wd)/7);
drh7014aff2003-11-01 01:53:53 +0000882 j += 2;
883 }else{
drh5bb3eb92007-05-04 13:15:55 +0000884 sqlite3_snprintf(4, &z[j],"%03d",nDay+1);
drh7014aff2003-11-01 01:53:53 +0000885 j += 3;
886 }
887 break;
888 }
drh5bb3eb92007-05-04 13:15:55 +0000889 case 'J': {
890 sqlite3_snprintf(20, &z[j],"%.16g",x.rJD);
891 j+=strlen(&z[j]);
892 break;
893 }
894 case 'm': sqlite3_snprintf(3, &z[j],"%02d",x.M); j+=2; break;
895 case 'M': sqlite3_snprintf(3, &z[j],"%02d",x.m); j+=2; break;
drh7014aff2003-11-01 01:53:53 +0000896 case 's': {
drh5bb3eb92007-05-04 13:15:55 +0000897 sqlite3_snprintf(30,&z[j],"%d",
898 (int)((x.rJD-2440587.5)*86400.0 + 0.5));
drh7014aff2003-11-01 01:53:53 +0000899 j += strlen(&z[j]);
900 break;
901 }
drh5bb3eb92007-05-04 13:15:55 +0000902 case 'S': sqlite3_snprintf(3,&z[j],"%02d",(int)x.s); j+=2; break;
drh7014aff2003-11-01 01:53:53 +0000903 case 'w': z[j++] = (((int)(x.rJD+1.5)) % 7) + '0'; break;
drh5bb3eb92007-05-04 13:15:55 +0000904 case 'Y': sqlite3_snprintf(5,&z[j],"%04d",x.Y); j+=strlen(&z[j]);break;
drh008e4762008-01-17 22:27:53 +0000905 default: z[j++] = '%'; break;
drh7014aff2003-11-01 01:53:53 +0000906 }
907 }
908 }
909 z[j] = 0;
drh3334e942008-01-17 20:26:46 +0000910 sqlite3_result_text(context, z, -1,
911 z==zBuf ? SQLITE_TRANSIENT : sqlite3_free);
drh7014aff2003-11-01 01:53:53 +0000912}
913
danielk19777977a172004-11-09 12:44:37 +0000914/*
915** current_time()
916**
917** This function returns the same value as time('now').
918*/
919static void ctimeFunc(
920 sqlite3_context *context,
921 int argc,
922 sqlite3_value **argv
923){
drh008e4762008-01-17 22:27:53 +0000924 timeFunc(context, 0, 0);
danielk19777977a172004-11-09 12:44:37 +0000925}
drh7014aff2003-11-01 01:53:53 +0000926
danielk19777977a172004-11-09 12:44:37 +0000927/*
928** current_date()
929**
930** This function returns the same value as date('now').
931*/
932static void cdateFunc(
933 sqlite3_context *context,
934 int argc,
935 sqlite3_value **argv
936){
drh008e4762008-01-17 22:27:53 +0000937 dateFunc(context, 0, 0);
danielk19777977a172004-11-09 12:44:37 +0000938}
939
940/*
941** current_timestamp()
942**
943** This function returns the same value as datetime('now').
944*/
945static void ctimestampFunc(
946 sqlite3_context *context,
947 int argc,
948 sqlite3_value **argv
949){
drh008e4762008-01-17 22:27:53 +0000950 datetimeFunc(context, 0, 0);
danielk19777977a172004-11-09 12:44:37 +0000951}
drh7014aff2003-11-01 01:53:53 +0000952#endif /* !defined(SQLITE_OMIT_DATETIME_FUNCS) */
953
danielk1977752e6792004-11-09 16:13:33 +0000954#ifdef SQLITE_OMIT_DATETIME_FUNCS
955/*
956** If the library is compiled to omit the full-scale date and time
957** handling (to get a smaller binary), the following minimal version
958** of the functions current_time(), current_date() and current_timestamp()
959** are included instead. This is to support column declarations that
960** include "DEFAULT CURRENT_TIME" etc.
961**
danielk19772df9fab2004-11-11 01:50:30 +0000962** This function uses the C-library functions time(), gmtime()
danielk1977752e6792004-11-09 16:13:33 +0000963** and strftime(). The format string to pass to strftime() is supplied
964** as the user-data for the function.
965*/
danielk1977752e6792004-11-09 16:13:33 +0000966static void currentTimeFunc(
967 sqlite3_context *context,
968 int argc,
969 sqlite3_value **argv
970){
971 time_t t;
972 char *zFormat = (char *)sqlite3_user_data(context);
973 char zBuf[20];
danielk1977752e6792004-11-09 16:13:33 +0000974
danielk1977752e6792004-11-09 16:13:33 +0000975 time(&t);
976#ifdef SQLITE_TEST
drh6c626082004-11-14 21:56:29 +0000977 {
978 extern int sqlite3_current_time; /* See os_XXX.c */
979 if( sqlite3_current_time ){
980 t = sqlite3_current_time;
981 }
danielk1977752e6792004-11-09 16:13:33 +0000982 }
983#endif
danielk1977e6efa742004-11-10 11:55:10 +0000984
drh87595762006-09-08 12:49:43 +0000985#ifdef HAVE_GMTIME_R
986 {
987 struct tm sNow;
988 gmtime_r(&t, &sNow);
989 strftime(zBuf, 20, zFormat, &sNow);
990 }
991#else
992 {
993 struct tm *pTm;
danielk19774152e672007-09-12 17:01:45 +0000994 sqlite3_mutex_enter(sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_MASTER));
drh87595762006-09-08 12:49:43 +0000995 pTm = gmtime(&t);
996 strftime(zBuf, 20, zFormat, pTm);
danielk19774152e672007-09-12 17:01:45 +0000997 sqlite3_mutex_leave(sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_MASTER));
drh87595762006-09-08 12:49:43 +0000998 }
999#endif
danielk1977e6efa742004-11-10 11:55:10 +00001000
danielk1977752e6792004-11-09 16:13:33 +00001001 sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
1002}
1003#endif
1004
drh7014aff2003-11-01 01:53:53 +00001005/*
1006** This function registered all of the above C functions as SQL
1007** functions. This should be the only routine in this file with
1008** external linkage.
1009*/
drh9bb575f2004-09-06 17:24:11 +00001010void sqlite3RegisterDateTimeFunctions(sqlite3 *db){
drhfd1f3942004-07-20 00:39:14 +00001011#ifndef SQLITE_OMIT_DATETIME_FUNCS
drh57196282004-10-06 15:41:16 +00001012 static const struct {
drh7014aff2003-11-01 01:53:53 +00001013 char *zName;
1014 int nArg;
danielk19770ae8b832004-05-25 12:05:56 +00001015 void (*xFunc)(sqlite3_context*,int,sqlite3_value**);
drh7014aff2003-11-01 01:53:53 +00001016 } aFuncs[] = {
drhf9b596e2004-05-26 16:54:42 +00001017 { "julianday", -1, juliandayFunc },
1018 { "date", -1, dateFunc },
1019 { "time", -1, timeFunc },
1020 { "datetime", -1, datetimeFunc },
1021 { "strftime", -1, strftimeFunc },
danielk19777977a172004-11-09 12:44:37 +00001022 { "current_time", 0, ctimeFunc },
1023 { "current_timestamp", 0, ctimestampFunc },
1024 { "current_date", 0, cdateFunc },
drh7014aff2003-11-01 01:53:53 +00001025 };
1026 int i;
1027
1028 for(i=0; i<sizeof(aFuncs)/sizeof(aFuncs[0]); i++){
danielk1977771151b2006-01-17 13:21:40 +00001029 sqlite3CreateFunc(db, aFuncs[i].zName, aFuncs[i].nArg,
danielk1977fee2d252007-08-18 10:59:19 +00001030 SQLITE_UTF8, (void *)(db->pVfs), aFuncs[i].xFunc, 0, 0);
drh7014aff2003-11-01 01:53:53 +00001031 }
danielk1977752e6792004-11-09 16:13:33 +00001032#else
1033 static const struct {
1034 char *zName;
1035 char *zFormat;
1036 } aFuncs[] = {
1037 { "current_time", "%H:%M:%S" },
1038 { "current_date", "%Y-%m-%d" },
1039 { "current_timestamp", "%Y-%m-%d %H:%M:%S" }
1040 };
1041 int i;
1042
1043 for(i=0; i<sizeof(aFuncs)/sizeof(aFuncs[0]); i++){
danielk1977771151b2006-01-17 13:21:40 +00001044 sqlite3CreateFunc(db, aFuncs[i].zName, 0, SQLITE_UTF8,
danielk1977752e6792004-11-09 16:13:33 +00001045 aFuncs[i].zFormat, currentTimeFunc, 0, 0);
1046 }
drhfd1f3942004-07-20 00:39:14 +00001047#endif
drh7014aff2003-11-01 01:53:53 +00001048}