blob: 4629ebac92567681523e4ff68ca8f20b9acc732f [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**
danielk1977fee2d252007-08-18 10:59:19 +000019** $Id: date.c,v 1.69 2007/08/18 10:59:20 danielk1977 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"
drheb206252004-10-01 02:00:31 +000049#include "os.h"
drh7014aff2003-11-01 01:53:53 +000050#include <ctype.h>
51#include <stdlib.h>
52#include <assert.h>
drh7091cb02003-12-23 16:22:18 +000053#include <time.h>
drh7014aff2003-11-01 01:53:53 +000054
drh4bc05852004-02-10 13:19:35 +000055#ifndef SQLITE_OMIT_DATETIME_FUNCS
56
drh7014aff2003-11-01 01:53:53 +000057/*
58** A structure for holding a single date and time.
59*/
60typedef struct DateTime DateTime;
61struct DateTime {
62 double rJD; /* The julian day number */
63 int Y, M, D; /* Year, month, and day */
64 int h, m; /* Hour and minutes */
65 int tz; /* Timezone offset in minutes */
66 double s; /* Seconds */
67 char validYMD; /* True if Y,M,D are valid */
68 char validHMS; /* True if h,m,s are valid */
69 char validJD; /* True if rJD is valid */
70 char validTZ; /* True if tz is valid */
71};
72
73
74/*
drheb9a9e82004-02-22 17:49:32 +000075** Convert zDate into one or more integers. Additional arguments
76** come in groups of 5 as follows:
77**
78** N number of digits in the integer
79** min minimum allowed value of the integer
80** max maximum allowed value of the integer
81** nextC first character after the integer
82** pVal where to write the integers value.
83**
84** Conversions continue until one with nextC==0 is encountered.
85** The function returns the number of successful conversions.
drh7014aff2003-11-01 01:53:53 +000086*/
drheb9a9e82004-02-22 17:49:32 +000087static int getDigits(const char *zDate, ...){
88 va_list ap;
89 int val;
90 int N;
91 int min;
92 int max;
93 int nextC;
94 int *pVal;
95 int cnt = 0;
96 va_start(ap, zDate);
97 do{
98 N = va_arg(ap, int);
99 min = va_arg(ap, int);
100 max = va_arg(ap, int);
101 nextC = va_arg(ap, int);
102 pVal = va_arg(ap, int*);
103 val = 0;
104 while( N-- ){
drh4c755c02004-08-08 20:22:17 +0000105 if( !isdigit(*(u8*)zDate) ){
drh029b44b2006-01-15 00:13:15 +0000106 goto end_getDigits;
drheb9a9e82004-02-22 17:49:32 +0000107 }
108 val = val*10 + *zDate - '0';
109 zDate++;
110 }
111 if( val<min || val>max || (nextC!=0 && nextC!=*zDate) ){
drh029b44b2006-01-15 00:13:15 +0000112 goto end_getDigits;
drheb9a9e82004-02-22 17:49:32 +0000113 }
114 *pVal = val;
drh7014aff2003-11-01 01:53:53 +0000115 zDate++;
drheb9a9e82004-02-22 17:49:32 +0000116 cnt++;
117 }while( nextC );
drh029b44b2006-01-15 00:13:15 +0000118end_getDigits:
drh15b9a152006-01-31 20:49:13 +0000119 va_end(ap);
drheb9a9e82004-02-22 17:49:32 +0000120 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*/
drh487e2622005-06-25 18:42:14 +0000127#define getValue sqlite3AtoF
drh7014aff2003-11-01 01:53:53 +0000128
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;
drh4c755c02004-08-08 20:22:17 +0000144 while( isspace(*(u8*)zDate) ){ zDate++; }
drh7014aff2003-11-01 01:53:53 +0000145 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++;
drheb9a9e82004-02-22 17:49:32 +0000154 if( getDigits(zDate, 2, 0, 14, ':', &nHr, 2, 0, 59, 0, &nMn)!=2 ){
155 return 1;
156 }
157 zDate += 5;
drh7014aff2003-11-01 01:53:53 +0000158 p->tz = sgn*(nMn + nHr*60);
drh4c755c02004-08-08 20:22:17 +0000159 while( isspace(*(u8*)zDate) ){ zDate++; }
drh7014aff2003-11-01 01:53:53 +0000160 return *zDate!=0;
161}
162
163/*
164** Parse times of the form HH:MM or HH:MM:SS or HH:MM:SS.FFFF.
165** The HH, MM, and SS must each be exactly 2 digits. The
166** fractional seconds FFFF can be one or more digits.
167**
168** Return 1 if there is a parsing error and 0 on success.
169*/
170static int parseHhMmSs(const char *zDate, DateTime *p){
171 int h, m, s;
172 double ms = 0.0;
drheb9a9e82004-02-22 17:49:32 +0000173 if( getDigits(zDate, 2, 0, 24, ':', &h, 2, 0, 59, 0, &m)!=2 ){
174 return 1;
175 }
176 zDate += 5;
drh7014aff2003-11-01 01:53:53 +0000177 if( *zDate==':' ){
drheb9a9e82004-02-22 17:49:32 +0000178 zDate++;
179 if( getDigits(zDate, 2, 0, 59, 0, &s)!=1 ){
180 return 1;
181 }
182 zDate += 2;
drh4c755c02004-08-08 20:22:17 +0000183 if( *zDate=='.' && isdigit((u8)zDate[1]) ){
drh7014aff2003-11-01 01:53:53 +0000184 double rScale = 1.0;
185 zDate++;
drh4c755c02004-08-08 20:22:17 +0000186 while( isdigit(*(u8*)zDate) ){
drh7014aff2003-11-01 01:53:53 +0000187 ms = ms*10.0 + *zDate - '0';
188 rScale *= 10.0;
189 zDate++;
190 }
191 ms /= rScale;
192 }
193 }else{
194 s = 0;
195 }
196 p->validJD = 0;
197 p->validHMS = 1;
198 p->h = h;
199 p->m = m;
200 p->s = s + ms;
201 if( parseTimezone(zDate, p) ) return 1;
202 p->validTZ = p->tz!=0;
203 return 0;
204}
205
206/*
207** Convert from YYYY-MM-DD HH:MM:SS to julian day. We always assume
208** that the YYYY-MM-DD is according to the Gregorian calendar.
209**
210** Reference: Meeus page 61
211*/
212static void computeJD(DateTime *p){
213 int Y, M, D, A, B, X1, X2;
214
215 if( p->validJD ) return;
216 if( p->validYMD ){
217 Y = p->Y;
218 M = p->M;
219 D = p->D;
220 }else{
drhba212562004-01-08 02:17:31 +0000221 Y = 2000; /* If no YMD specified, assume 2000-Jan-01 */
drh7014aff2003-11-01 01:53:53 +0000222 M = 1;
223 D = 1;
224 }
225 if( M<=2 ){
226 Y--;
227 M += 12;
228 }
229 A = Y/100;
230 B = 2 - A + (A/4);
231 X1 = 365.25*(Y+4716);
232 X2 = 30.6001*(M+1);
233 p->rJD = X1 + X2 + D + B - 1524.5;
234 p->validJD = 1;
drh7014aff2003-11-01 01:53:53 +0000235 if( p->validHMS ){
236 p->rJD += (p->h*3600.0 + p->m*60.0 + p->s)/86400.0;
237 if( p->validTZ ){
drh57391032006-01-09 00:18:02 +0000238 p->rJD -= p->tz*60/86400.0;
drhf11c34d2006-09-08 12:27:36 +0000239 p->validYMD = 0;
drh7014aff2003-11-01 01:53:53 +0000240 p->validHMS = 0;
241 p->validTZ = 0;
242 }
243 }
244}
245
246/*
247** Parse dates of the form
248**
249** YYYY-MM-DD HH:MM:SS.FFF
250** YYYY-MM-DD HH:MM:SS
251** YYYY-MM-DD HH:MM
252** YYYY-MM-DD
253**
254** Write the result into the DateTime structure and return 0
255** on success and 1 if the input string is not a well-formed
256** date.
257*/
258static int parseYyyyMmDd(const char *zDate, DateTime *p){
drh8eb2cce2004-02-21 03:28:18 +0000259 int Y, M, D, neg;
drh7014aff2003-11-01 01:53:53 +0000260
drh8eb2cce2004-02-21 03:28:18 +0000261 if( zDate[0]=='-' ){
262 zDate++;
263 neg = 1;
264 }else{
265 neg = 0;
266 }
drheb9a9e82004-02-22 17:49:32 +0000267 if( getDigits(zDate,4,0,9999,'-',&Y,2,1,12,'-',&M,2,1,31,0,&D)!=3 ){
268 return 1;
269 }
270 zDate += 10;
drh4cb29b42005-03-21 00:43:44 +0000271 while( isspace(*(u8*)zDate) || 'T'==*(u8*)zDate ){ zDate++; }
drheb9a9e82004-02-22 17:49:32 +0000272 if( parseHhMmSs(zDate, p)==0 ){
273 /* We got the time */
drh7014aff2003-11-01 01:53:53 +0000274 }else if( *zDate==0 ){
275 p->validHMS = 0;
276 }else{
277 return 1;
278 }
279 p->validJD = 0;
280 p->validYMD = 1;
drh8eb2cce2004-02-21 03:28:18 +0000281 p->Y = neg ? -Y : Y;
drh7014aff2003-11-01 01:53:53 +0000282 p->M = M;
283 p->D = D;
284 if( p->validTZ ){
285 computeJD(p);
286 }
287 return 0;
288}
289
290/*
291** Attempt to parse the given string into a Julian Day Number. Return
292** the number of errors.
293**
294** The following are acceptable forms for the input string:
295**
296** YYYY-MM-DD HH:MM:SS.FFF +/-HH:MM
297** DDDD.DD
298** now
299**
300** In the first form, the +/-HH:MM is always optional. The fractional
301** seconds extension (the ".FFF") is optional. The seconds portion
302** (":SS.FFF") is option. The year and date can be omitted as long
303** as there is a time string. The time string can be omitted as long
304** as there is a year and date.
305*/
danielk1977fee2d252007-08-18 10:59:19 +0000306static int parseDateOrTime(
307 sqlite3_context *context,
308 const char *zDate,
309 DateTime *p
310){
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;
danielk19774adee202004-05-08 08:23:19 +0000316 }else if( sqlite3StrICmp(zDate,"now")==0){
drh7014aff2003-11-01 01:53:53 +0000317 double r;
danielk1977fee2d252007-08-18 10:59:19 +0000318 sqlite3OsCurrentTime((sqlite3_vfs *)sqlite3_user_data(context), &r);
drh018d1a42005-01-15 01:52:31 +0000319 p->rJD = r;
320 p->validJD = 1;
321 return 0;
danielk1977dc8453f2004-06-12 00:42:34 +0000322 }else if( sqlite3IsNumber(zDate, 0, SQLITE_UTF8) ){
drh487e2622005-06-25 18:42:14 +0000323 getValue(zDate, &p->rJD);
drh7014aff2003-11-01 01:53:53 +0000324 p->validJD = 1;
325 return 0;
326 }
327 return 1;
328}
329
330/*
331** Compute the Year, Month, and Day from the julian day number.
332*/
333static void computeYMD(DateTime *p){
334 int Z, A, B, C, D, E, X1;
335 if( p->validYMD ) return;
drh33a9ad22004-02-29 00:40:32 +0000336 if( !p->validJD ){
337 p->Y = 2000;
338 p->M = 1;
339 p->D = 1;
340 }else{
341 Z = p->rJD + 0.5;
342 A = (Z - 1867216.25)/36524.25;
343 A = Z + 1 + A - (A/4);
344 B = A + 1524;
345 C = (B - 122.1)/365.25;
346 D = 365.25*C;
347 E = (B-D)/30.6001;
348 X1 = 30.6001*E;
349 p->D = B - D - X1;
350 p->M = E<14 ? E-1 : E-13;
351 p->Y = p->M>2 ? C - 4716 : C - 4715;
352 }
drh7014aff2003-11-01 01:53:53 +0000353 p->validYMD = 1;
354}
355
356/*
357** Compute the Hour, Minute, and Seconds from the julian day number.
358*/
359static void computeHMS(DateTime *p){
360 int Z, s;
361 if( p->validHMS ) return;
drhf11c34d2006-09-08 12:27:36 +0000362 computeJD(p);
drh7014aff2003-11-01 01:53:53 +0000363 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;
drh7091cb02003-12-23 16:22:18 +0000399 x = *p;
drhba212562004-01-08 02:17:31 +0000400 computeYMD_HMS(&x);
drh7091cb02003-12-23 16:22:18 +0000401 if( x.Y<1971 || x.Y>=2038 ){
402 x.Y = 2000;
403 x.M = 1;
404 x.D = 1;
405 x.h = 0;
406 x.m = 0;
407 x.s = 0.0;
408 } else {
409 int s = x.s + 0.5;
410 x.s = s;
411 }
412 x.tz = 0;
413 x.validJD = 0;
414 computeJD(&x);
415 t = (x.rJD-2440587.5)*86400.0 + 0.5;
drh87595762006-09-08 12:49:43 +0000416#ifdef HAVE_LOCALTIME_R
417 {
418 struct tm sLocal;
419 localtime_r(&t, &sLocal);
420 y.Y = sLocal.tm_year + 1900;
421 y.M = sLocal.tm_mon + 1;
422 y.D = sLocal.tm_mday;
423 y.h = sLocal.tm_hour;
424 y.m = sLocal.tm_min;
425 y.s = sLocal.tm_sec;
426 }
427#else
428 {
429 struct tm *pTm;
danielk1977fee2d252007-08-18 10:59:19 +0000430 sqlite3_mutex_enter(sqlite3_mutex_alloc(SQLITE_MUTEX_GLOBAL));
drh87595762006-09-08 12:49:43 +0000431 pTm = localtime(&t);
432 y.Y = pTm->tm_year + 1900;
433 y.M = pTm->tm_mon + 1;
434 y.D = pTm->tm_mday;
435 y.h = pTm->tm_hour;
436 y.m = pTm->tm_min;
437 y.s = pTm->tm_sec;
danielk1977fee2d252007-08-18 10:59:19 +0000438 sqlite3_mutex_leave(sqlite3_mutex_alloc(SQLITE_MUTEX_GLOBAL));
drh87595762006-09-08 12:49:43 +0000439 }
440#endif
drh7091cb02003-12-23 16:22:18 +0000441 y.validYMD = 1;
442 y.validHMS = 1;
443 y.validJD = 0;
444 y.validTZ = 0;
445 computeJD(&y);
drh7091cb02003-12-23 16:22:18 +0000446 return y.rJD - x.rJD;
447}
448
449/*
drh7014aff2003-11-01 01:53:53 +0000450** Process a modifier to a date-time stamp. The modifiers are
451** as follows:
452**
453** NNN days
454** NNN hours
455** NNN minutes
456** NNN.NNNN seconds
457** NNN months
458** NNN years
459** start of month
460** start of year
461** start of week
462** start of day
463** weekday N
464** unixepoch
drh7091cb02003-12-23 16:22:18 +0000465** localtime
466** utc
drh7014aff2003-11-01 01:53:53 +0000467**
468** Return 0 on success and 1 if there is any kind of error.
469*/
470static int parseModifier(const char *zMod, DateTime *p){
471 int rc = 1;
472 int n;
473 double r;
drh4d5b8362004-01-17 01:16:21 +0000474 char *z, zBuf[30];
475 z = zBuf;
476 for(n=0; n<sizeof(zBuf)-1 && zMod[n]; n++){
drh7014aff2003-11-01 01:53:53 +0000477 z[n] = tolower(zMod[n]);
478 }
479 z[n] = 0;
480 switch( z[0] ){
drh7091cb02003-12-23 16:22:18 +0000481 case 'l': {
482 /* localtime
483 **
484 ** Assuming the current time value is UTC (a.k.a. GMT), shift it to
485 ** show local time.
486 */
487 if( strcmp(z, "localtime")==0 ){
488 computeJD(p);
489 p->rJD += localtimeOffset(p);
drhba212562004-01-08 02:17:31 +0000490 clearYMD_HMS_TZ(p);
drh7091cb02003-12-23 16:22:18 +0000491 rc = 0;
492 }
493 break;
494 }
drh7014aff2003-11-01 01:53:53 +0000495 case 'u': {
496 /*
497 ** unixepoch
498 **
499 ** Treat the current value of p->rJD as the number of
500 ** seconds since 1970. Convert to a real julian day number.
501 */
502 if( strcmp(z, "unixepoch")==0 && p->validJD ){
503 p->rJD = p->rJD/86400.0 + 2440587.5;
drhba212562004-01-08 02:17:31 +0000504 clearYMD_HMS_TZ(p);
drh7014aff2003-11-01 01:53:53 +0000505 rc = 0;
drh7091cb02003-12-23 16:22:18 +0000506 }else if( strcmp(z, "utc")==0 ){
507 double c1;
508 computeJD(p);
509 c1 = localtimeOffset(p);
510 p->rJD -= c1;
drhba212562004-01-08 02:17:31 +0000511 clearYMD_HMS_TZ(p);
drh7091cb02003-12-23 16:22:18 +0000512 p->rJD += c1 - localtimeOffset(p);
drh7091cb02003-12-23 16:22:18 +0000513 rc = 0;
drh7014aff2003-11-01 01:53:53 +0000514 }
515 break;
516 }
517 case 'w': {
518 /*
519 ** weekday N
520 **
drh181fc992004-08-17 10:42:54 +0000521 ** Move the date to the same time on the next occurrence of
drh7014aff2003-11-01 01:53:53 +0000522 ** weekday N where 0==Sunday, 1==Monday, and so forth. If the
drhc5dd9fa2004-01-07 03:29:16 +0000523 ** date is already on the appropriate weekday, this is a no-op.
drh7014aff2003-11-01 01:53:53 +0000524 */
525 if( strncmp(z, "weekday ", 8)==0 && getValue(&z[8],&r)>0
526 && (n=r)==r && n>=0 && r<7 ){
527 int Z;
drhba212562004-01-08 02:17:31 +0000528 computeYMD_HMS(p);
drh7014aff2003-11-01 01:53:53 +0000529 p->validTZ = 0;
530 p->validJD = 0;
531 computeJD(p);
532 Z = p->rJD + 1.5;
533 Z %= 7;
534 if( Z>n ) Z -= 7;
535 p->rJD += n - Z;
drhba212562004-01-08 02:17:31 +0000536 clearYMD_HMS_TZ(p);
drh7014aff2003-11-01 01:53:53 +0000537 rc = 0;
538 }
539 break;
540 }
541 case 's': {
542 /*
543 ** start of TTTTT
544 **
545 ** Move the date backwards to the beginning of the current day,
546 ** or month or year.
547 */
548 if( strncmp(z, "start of ", 9)!=0 ) break;
drh4d5b8362004-01-17 01:16:21 +0000549 z += 9;
drh7014aff2003-11-01 01:53:53 +0000550 computeYMD(p);
551 p->validHMS = 1;
552 p->h = p->m = 0;
553 p->s = 0.0;
554 p->validTZ = 0;
555 p->validJD = 0;
drh4d5b8362004-01-17 01:16:21 +0000556 if( strcmp(z,"month")==0 ){
drh7014aff2003-11-01 01:53:53 +0000557 p->D = 1;
558 rc = 0;
drh4d5b8362004-01-17 01:16:21 +0000559 }else if( strcmp(z,"year")==0 ){
drh7014aff2003-11-01 01:53:53 +0000560 computeYMD(p);
561 p->M = 1;
562 p->D = 1;
563 rc = 0;
drh4d5b8362004-01-17 01:16:21 +0000564 }else if( strcmp(z,"day")==0 ){
drh7014aff2003-11-01 01:53:53 +0000565 rc = 0;
566 }
567 break;
568 }
569 case '+':
570 case '-':
571 case '0':
572 case '1':
573 case '2':
574 case '3':
575 case '4':
576 case '5':
577 case '6':
578 case '7':
579 case '8':
580 case '9': {
581 n = getValue(z, &r);
drh05f7c192007-04-06 02:32:33 +0000582 assert( n>=1 );
drh33a9ad22004-02-29 00:40:32 +0000583 if( z[n]==':' ){
584 /* A modifier of the form (+|-)HH:MM:SS.FFF adds (or subtracts) the
585 ** specified number of hours, minutes, seconds, and fractional seconds
586 ** to the time. The ".FFF" may be omitted. The ":SS.FFF" may be
587 ** omitted.
588 */
589 const char *z2 = z;
590 DateTime tx;
591 int day;
drh4c755c02004-08-08 20:22:17 +0000592 if( !isdigit(*(u8*)z2) ) z2++;
drh33a9ad22004-02-29 00:40:32 +0000593 memset(&tx, 0, sizeof(tx));
594 if( parseHhMmSs(z2, &tx) ) break;
595 computeJD(&tx);
drh0d131ab2004-02-29 01:08:17 +0000596 tx.rJD -= 0.5;
drh33a9ad22004-02-29 00:40:32 +0000597 day = (int)tx.rJD;
drhb6829e92004-02-29 00:50:33 +0000598 tx.rJD -= day;
drhb6829e92004-02-29 00:50:33 +0000599 if( z[0]=='-' ) tx.rJD = -tx.rJD;
drh0d131ab2004-02-29 01:08:17 +0000600 computeJD(p);
601 clearYMD_HMS_TZ(p);
drhf11c34d2006-09-08 12:27:36 +0000602 p->rJD += tx.rJD;
drh33a9ad22004-02-29 00:40:32 +0000603 rc = 0;
604 break;
605 }
drh4d5b8362004-01-17 01:16:21 +0000606 z += n;
drh4c755c02004-08-08 20:22:17 +0000607 while( isspace(*(u8*)z) ) z++;
drh4d5b8362004-01-17 01:16:21 +0000608 n = strlen(z);
drh7014aff2003-11-01 01:53:53 +0000609 if( n>10 || n<3 ) break;
drh7014aff2003-11-01 01:53:53 +0000610 if( z[n-1]=='s' ){ z[n-1] = 0; n--; }
611 computeJD(p);
612 rc = 0;
613 if( n==3 && strcmp(z,"day")==0 ){
614 p->rJD += r;
615 }else if( n==4 && strcmp(z,"hour")==0 ){
drh7014aff2003-11-01 01:53:53 +0000616 p->rJD += r/24.0;
617 }else if( n==6 && strcmp(z,"minute")==0 ){
drh7014aff2003-11-01 01:53:53 +0000618 p->rJD += r/(24.0*60.0);
619 }else if( n==6 && strcmp(z,"second")==0 ){
drh7014aff2003-11-01 01:53:53 +0000620 p->rJD += r/(24.0*60.0*60.0);
621 }else if( n==5 && strcmp(z,"month")==0 ){
622 int x, y;
drhba212562004-01-08 02:17:31 +0000623 computeYMD_HMS(p);
drh7014aff2003-11-01 01:53:53 +0000624 p->M += r;
625 x = p->M>0 ? (p->M-1)/12 : (p->M-12)/12;
626 p->Y += x;
627 p->M -= x*12;
628 p->validJD = 0;
629 computeJD(p);
630 y = r;
631 if( y!=r ){
632 p->rJD += (r - y)*30.0;
633 }
634 }else if( n==4 && strcmp(z,"year")==0 ){
drhba212562004-01-08 02:17:31 +0000635 computeYMD_HMS(p);
drh7014aff2003-11-01 01:53:53 +0000636 p->Y += r;
637 p->validJD = 0;
638 computeJD(p);
639 }else{
640 rc = 1;
641 }
drhba212562004-01-08 02:17:31 +0000642 clearYMD_HMS_TZ(p);
drh7014aff2003-11-01 01:53:53 +0000643 break;
644 }
645 default: {
646 break;
647 }
648 }
649 return rc;
650}
651
652/*
653** Process time function arguments. argv[0] is a date-time stamp.
654** argv[1] and following are modifiers. Parse them all and write
655** the resulting time into the DateTime structure p. Return 0
656** on success and 1 if there are any errors.
657*/
danielk1977fee2d252007-08-18 10:59:19 +0000658static int isDate(
659 sqlite3_context *context,
660 int argc,
661 sqlite3_value **argv,
662 DateTime *p
663){
drh7014aff2003-11-01 01:53:53 +0000664 int i;
drh7a521cf2007-04-25 18:23:52 +0000665 const unsigned char *z;
drh7014aff2003-11-01 01:53:53 +0000666 if( argc==0 ) return 1;
danielk1977fee2d252007-08-18 10:59:19 +0000667 z = sqlite3_value_text(argv[0]);
668 if( !z || parseDateOrTime(context, (char*)z, p) ){
drh7a521cf2007-04-25 18:23:52 +0000669 return 1;
670 }
drh7014aff2003-11-01 01:53:53 +0000671 for(i=1; i<argc; i++){
drh7a521cf2007-04-25 18:23:52 +0000672 if( (z = sqlite3_value_text(argv[i]))==0 || parseModifier((char*)z, p) ){
673 return 1;
674 }
drh7014aff2003-11-01 01:53:53 +0000675 }
676 return 0;
677}
678
679
680/*
681** The following routines implement the various date and time functions
682** of SQLite.
683*/
684
685/*
686** julianday( TIMESTRING, MOD, MOD, ...)
687**
688** Return the julian day number of the date specified in the arguments
689*/
drhf9b596e2004-05-26 16:54:42 +0000690static void juliandayFunc(
691 sqlite3_context *context,
692 int argc,
693 sqlite3_value **argv
694){
drh7014aff2003-11-01 01:53:53 +0000695 DateTime x;
danielk1977fee2d252007-08-18 10:59:19 +0000696 if( isDate(context, argc, argv, &x)==0 ){
drh7014aff2003-11-01 01:53:53 +0000697 computeJD(&x);
danielk19777e18c252004-05-25 11:47:24 +0000698 sqlite3_result_double(context, x.rJD);
drh7014aff2003-11-01 01:53:53 +0000699 }
700}
701
702/*
703** datetime( TIMESTRING, MOD, MOD, ...)
704**
705** Return YYYY-MM-DD HH:MM:SS
706*/
drhf9b596e2004-05-26 16:54:42 +0000707static void datetimeFunc(
708 sqlite3_context *context,
709 int argc,
710 sqlite3_value **argv
711){
drh7014aff2003-11-01 01:53:53 +0000712 DateTime x;
danielk1977fee2d252007-08-18 10:59:19 +0000713 if( isDate(context, argc, argv, &x)==0 ){
drh7014aff2003-11-01 01:53:53 +0000714 char zBuf[100];
drhba212562004-01-08 02:17:31 +0000715 computeYMD_HMS(&x);
drh5bb3eb92007-05-04 13:15:55 +0000716 sqlite3_snprintf(sizeof(zBuf), zBuf, "%04d-%02d-%02d %02d:%02d:%02d",
717 x.Y, x.M, x.D, x.h, x.m, (int)(x.s));
danielk1977d8123362004-06-12 09:25:12 +0000718 sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
drh7014aff2003-11-01 01:53:53 +0000719 }
720}
721
722/*
723** time( TIMESTRING, MOD, MOD, ...)
724**
725** Return HH:MM:SS
726*/
drhf9b596e2004-05-26 16:54:42 +0000727static void timeFunc(
728 sqlite3_context *context,
729 int argc,
730 sqlite3_value **argv
731){
drh7014aff2003-11-01 01:53:53 +0000732 DateTime x;
danielk1977fee2d252007-08-18 10:59:19 +0000733 if( isDate(context, argc, argv, &x)==0 ){
drh7014aff2003-11-01 01:53:53 +0000734 char zBuf[100];
735 computeHMS(&x);
drh5bb3eb92007-05-04 13:15:55 +0000736 sqlite3_snprintf(sizeof(zBuf), zBuf, "%02d:%02d:%02d", x.h, x.m, (int)x.s);
danielk1977d8123362004-06-12 09:25:12 +0000737 sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
drh7014aff2003-11-01 01:53:53 +0000738 }
739}
740
741/*
742** date( TIMESTRING, MOD, MOD, ...)
743**
744** Return YYYY-MM-DD
745*/
drhf9b596e2004-05-26 16:54:42 +0000746static void dateFunc(
747 sqlite3_context *context,
748 int argc,
749 sqlite3_value **argv
750){
drh7014aff2003-11-01 01:53:53 +0000751 DateTime x;
danielk1977fee2d252007-08-18 10:59:19 +0000752 if( isDate(context, argc, argv, &x)==0 ){
drh7014aff2003-11-01 01:53:53 +0000753 char zBuf[100];
754 computeYMD(&x);
drh5bb3eb92007-05-04 13:15:55 +0000755 sqlite3_snprintf(sizeof(zBuf), zBuf, "%04d-%02d-%02d", x.Y, x.M, x.D);
danielk1977d8123362004-06-12 09:25:12 +0000756 sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
drh7014aff2003-11-01 01:53:53 +0000757 }
758}
759
760/*
761** strftime( FORMAT, TIMESTRING, MOD, MOD, ...)
762**
763** Return a string described by FORMAT. Conversions as follows:
764**
765** %d day of month
766** %f ** fractional seconds SS.SSS
767** %H hour 00-24
768** %j day of year 000-366
769** %J ** Julian day number
770** %m month 01-12
771** %M minute 00-59
772** %s seconds since 1970-01-01
773** %S seconds 00-59
774** %w day of week 0-6 sunday==0
775** %W week of year 00-53
776** %Y year 0000-9999
777** %% %
778*/
drhf9b596e2004-05-26 16:54:42 +0000779static void strftimeFunc(
780 sqlite3_context *context,
781 int argc,
782 sqlite3_value **argv
783){
drh7014aff2003-11-01 01:53:53 +0000784 DateTime x;
drha0206bc2007-05-08 15:15:02 +0000785 u64 n;
786 int i, j;
drh7014aff2003-11-01 01:53:53 +0000787 char *z;
drh2646da72005-12-09 20:02:05 +0000788 const char *zFmt = (const char*)sqlite3_value_text(argv[0]);
drh7014aff2003-11-01 01:53:53 +0000789 char zBuf[100];
danielk1977fee2d252007-08-18 10:59:19 +0000790 if( zFmt==0 || isDate(context, argc-1, argv+1, &x) ) return;
drh7014aff2003-11-01 01:53:53 +0000791 for(i=0, n=1; zFmt[i]; i++, n++){
792 if( zFmt[i]=='%' ){
793 switch( zFmt[i+1] ){
794 case 'd':
795 case 'H':
796 case 'm':
797 case 'M':
798 case 'S':
799 case 'W':
800 n++;
801 /* fall thru */
802 case 'w':
803 case '%':
804 break;
805 case 'f':
806 n += 8;
807 break;
808 case 'j':
809 n += 3;
810 break;
811 case 'Y':
812 n += 8;
813 break;
814 case 's':
815 case 'J':
816 n += 50;
817 break;
818 default:
819 return; /* ERROR. return a NULL */
820 }
821 i++;
822 }
823 }
824 if( n<sizeof(zBuf) ){
825 z = zBuf;
drha0206bc2007-05-08 15:15:02 +0000826 }else if( n>SQLITE_MAX_LENGTH ){
827 sqlite3_result_error_toobig(context);
828 return;
drh7014aff2003-11-01 01:53:53 +0000829 }else{
drh17435752007-08-16 04:30:38 +0000830 z = sqlite3_malloc( n );
drh7014aff2003-11-01 01:53:53 +0000831 if( z==0 ) return;
832 }
833 computeJD(&x);
drhba212562004-01-08 02:17:31 +0000834 computeYMD_HMS(&x);
drh7014aff2003-11-01 01:53:53 +0000835 for(i=j=0; zFmt[i]; i++){
836 if( zFmt[i]!='%' ){
837 z[j++] = zFmt[i];
838 }else{
839 i++;
840 switch( zFmt[i] ){
drh5bb3eb92007-05-04 13:15:55 +0000841 case 'd': sqlite3_snprintf(3, &z[j],"%02d",x.D); j+=2; break;
drh7014aff2003-11-01 01:53:53 +0000842 case 'f': {
drhb1f1e6e2006-09-25 18:01:31 +0000843 double s = x.s;
844 if( s>59.999 ) s = 59.999;
drh2ecad3b2007-03-29 17:57:21 +0000845 sqlite3_snprintf(7, &z[j],"%06.3f", s);
drh7014aff2003-11-01 01:53:53 +0000846 j += strlen(&z[j]);
847 break;
848 }
drh5bb3eb92007-05-04 13:15:55 +0000849 case 'H': sqlite3_snprintf(3, &z[j],"%02d",x.h); j+=2; break;
drh7014aff2003-11-01 01:53:53 +0000850 case 'W': /* Fall thru */
851 case 'j': {
danielk1977f0113002006-01-24 12:09:17 +0000852 int nDay; /* Number of days since 1st day of year */
drh7014aff2003-11-01 01:53:53 +0000853 DateTime y = x;
854 y.validJD = 0;
855 y.M = 1;
856 y.D = 1;
857 computeJD(&y);
drhc2c9eef2007-01-08 13:07:30 +0000858 nDay = x.rJD - y.rJD + 0.5;
drh7014aff2003-11-01 01:53:53 +0000859 if( zFmt[i]=='W' ){
drh1020d492004-07-18 22:22:43 +0000860 int wd; /* 0=Monday, 1=Tuesday, ... 6=Sunday */
861 wd = ((int)(x.rJD+0.5)) % 7;
drh5bb3eb92007-05-04 13:15:55 +0000862 sqlite3_snprintf(3, &z[j],"%02d",(nDay+7-wd)/7);
drh7014aff2003-11-01 01:53:53 +0000863 j += 2;
864 }else{
drh5bb3eb92007-05-04 13:15:55 +0000865 sqlite3_snprintf(4, &z[j],"%03d",nDay+1);
drh7014aff2003-11-01 01:53:53 +0000866 j += 3;
867 }
868 break;
869 }
drh5bb3eb92007-05-04 13:15:55 +0000870 case 'J': {
871 sqlite3_snprintf(20, &z[j],"%.16g",x.rJD);
872 j+=strlen(&z[j]);
873 break;
874 }
875 case 'm': sqlite3_snprintf(3, &z[j],"%02d",x.M); j+=2; break;
876 case 'M': sqlite3_snprintf(3, &z[j],"%02d",x.m); j+=2; break;
drh7014aff2003-11-01 01:53:53 +0000877 case 's': {
drh5bb3eb92007-05-04 13:15:55 +0000878 sqlite3_snprintf(30,&z[j],"%d",
879 (int)((x.rJD-2440587.5)*86400.0 + 0.5));
drh7014aff2003-11-01 01:53:53 +0000880 j += strlen(&z[j]);
881 break;
882 }
drh5bb3eb92007-05-04 13:15:55 +0000883 case 'S': sqlite3_snprintf(3,&z[j],"%02d",(int)x.s); j+=2; break;
drh7014aff2003-11-01 01:53:53 +0000884 case 'w': z[j++] = (((int)(x.rJD+1.5)) % 7) + '0'; break;
drh5bb3eb92007-05-04 13:15:55 +0000885 case 'Y': sqlite3_snprintf(5,&z[j],"%04d",x.Y); j+=strlen(&z[j]);break;
drh7014aff2003-11-01 01:53:53 +0000886 case '%': z[j++] = '%'; break;
887 }
888 }
889 }
890 z[j] = 0;
danielk1977d8123362004-06-12 09:25:12 +0000891 sqlite3_result_text(context, z, -1, SQLITE_TRANSIENT);
drh7014aff2003-11-01 01:53:53 +0000892 if( z!=zBuf ){
drh17435752007-08-16 04:30:38 +0000893 sqlite3_free(z);
drh7014aff2003-11-01 01:53:53 +0000894 }
895}
896
danielk19777977a172004-11-09 12:44:37 +0000897/*
898** current_time()
899**
900** This function returns the same value as time('now').
901*/
902static void ctimeFunc(
903 sqlite3_context *context,
904 int argc,
905 sqlite3_value **argv
906){
danielk19771e536952007-08-16 10:09:01 +0000907 sqlite3_value *pVal = sqlite3ValueNew(0);
danielk19777977a172004-11-09 12:44:37 +0000908 if( pVal ){
danielk19771e536952007-08-16 10:09:01 +0000909 sqlite3ValueSetStr(0, pVal, -1, "now", SQLITE_UTF8, SQLITE_STATIC);
danielk19777977a172004-11-09 12:44:37 +0000910 timeFunc(context, 1, &pVal);
911 sqlite3ValueFree(pVal);
912 }
913}
drh7014aff2003-11-01 01:53:53 +0000914
danielk19777977a172004-11-09 12:44:37 +0000915/*
916** current_date()
917**
918** This function returns the same value as date('now').
919*/
920static void cdateFunc(
921 sqlite3_context *context,
922 int argc,
923 sqlite3_value **argv
924){
danielk19771e536952007-08-16 10:09:01 +0000925 sqlite3_value *pVal = sqlite3ValueNew(0);
danielk19777977a172004-11-09 12:44:37 +0000926 if( pVal ){
danielk19771e536952007-08-16 10:09:01 +0000927 sqlite3ValueSetStr(0, pVal, -1, "now", SQLITE_UTF8, SQLITE_STATIC);
danielk19777977a172004-11-09 12:44:37 +0000928 dateFunc(context, 1, &pVal);
929 sqlite3ValueFree(pVal);
930 }
931}
932
933/*
934** current_timestamp()
935**
936** This function returns the same value as datetime('now').
937*/
938static void ctimestampFunc(
939 sqlite3_context *context,
940 int argc,
941 sqlite3_value **argv
942){
danielk19771e536952007-08-16 10:09:01 +0000943 sqlite3_value *pVal = sqlite3ValueNew(0);
danielk19777977a172004-11-09 12:44:37 +0000944 if( pVal ){
danielk19771e536952007-08-16 10:09:01 +0000945 sqlite3ValueSetStr(0, pVal, -1, "now", SQLITE_UTF8, SQLITE_STATIC);
danielk19777977a172004-11-09 12:44:37 +0000946 datetimeFunc(context, 1, &pVal);
947 sqlite3ValueFree(pVal);
948 }
949}
drh7014aff2003-11-01 01:53:53 +0000950#endif /* !defined(SQLITE_OMIT_DATETIME_FUNCS) */
951
danielk1977752e6792004-11-09 16:13:33 +0000952#ifdef SQLITE_OMIT_DATETIME_FUNCS
953/*
954** If the library is compiled to omit the full-scale date and time
955** handling (to get a smaller binary), the following minimal version
956** of the functions current_time(), current_date() and current_timestamp()
957** are included instead. This is to support column declarations that
958** include "DEFAULT CURRENT_TIME" etc.
959**
danielk19772df9fab2004-11-11 01:50:30 +0000960** This function uses the C-library functions time(), gmtime()
danielk1977752e6792004-11-09 16:13:33 +0000961** and strftime(). The format string to pass to strftime() is supplied
962** as the user-data for the function.
963*/
danielk1977752e6792004-11-09 16:13:33 +0000964static void currentTimeFunc(
965 sqlite3_context *context,
966 int argc,
967 sqlite3_value **argv
968){
969 time_t t;
970 char *zFormat = (char *)sqlite3_user_data(context);
971 char zBuf[20];
danielk1977752e6792004-11-09 16:13:33 +0000972
danielk1977752e6792004-11-09 16:13:33 +0000973 time(&t);
974#ifdef SQLITE_TEST
drh6c626082004-11-14 21:56:29 +0000975 {
976 extern int sqlite3_current_time; /* See os_XXX.c */
977 if( sqlite3_current_time ){
978 t = sqlite3_current_time;
979 }
danielk1977752e6792004-11-09 16:13:33 +0000980 }
981#endif
danielk1977e6efa742004-11-10 11:55:10 +0000982
drh87595762006-09-08 12:49:43 +0000983#ifdef HAVE_GMTIME_R
984 {
985 struct tm sNow;
986 gmtime_r(&t, &sNow);
987 strftime(zBuf, 20, zFormat, &sNow);
988 }
989#else
990 {
991 struct tm *pTm;
danielk1977fee2d252007-08-18 10:59:19 +0000992 sqlite3_mutex_enter(sqlite3_mutex_alloc(SQLITE_MUTEX_GLOBAL));
drh87595762006-09-08 12:49:43 +0000993 pTm = gmtime(&t);
994 strftime(zBuf, 20, zFormat, pTm);
danielk1977fee2d252007-08-18 10:59:19 +0000995 sqlite3_mutex_leave(sqlite3_mutex_alloc(SQLITE_MUTEX_GLOBAL));
drh87595762006-09-08 12:49:43 +0000996 }
997#endif
danielk1977e6efa742004-11-10 11:55:10 +0000998
danielk1977752e6792004-11-09 16:13:33 +0000999 sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
1000}
1001#endif
1002
drh7014aff2003-11-01 01:53:53 +00001003/*
1004** This function registered all of the above C functions as SQL
1005** functions. This should be the only routine in this file with
1006** external linkage.
1007*/
drh9bb575f2004-09-06 17:24:11 +00001008void sqlite3RegisterDateTimeFunctions(sqlite3 *db){
drhfd1f3942004-07-20 00:39:14 +00001009#ifndef SQLITE_OMIT_DATETIME_FUNCS
drh57196282004-10-06 15:41:16 +00001010 static const struct {
drh7014aff2003-11-01 01:53:53 +00001011 char *zName;
1012 int nArg;
danielk19770ae8b832004-05-25 12:05:56 +00001013 void (*xFunc)(sqlite3_context*,int,sqlite3_value**);
drh7014aff2003-11-01 01:53:53 +00001014 } aFuncs[] = {
drhf9b596e2004-05-26 16:54:42 +00001015 { "julianday", -1, juliandayFunc },
1016 { "date", -1, dateFunc },
1017 { "time", -1, timeFunc },
1018 { "datetime", -1, datetimeFunc },
1019 { "strftime", -1, strftimeFunc },
danielk19777977a172004-11-09 12:44:37 +00001020 { "current_time", 0, ctimeFunc },
1021 { "current_timestamp", 0, ctimestampFunc },
1022 { "current_date", 0, cdateFunc },
drh7014aff2003-11-01 01:53:53 +00001023 };
1024 int i;
1025
1026 for(i=0; i<sizeof(aFuncs)/sizeof(aFuncs[0]); i++){
danielk1977771151b2006-01-17 13:21:40 +00001027 sqlite3CreateFunc(db, aFuncs[i].zName, aFuncs[i].nArg,
danielk1977fee2d252007-08-18 10:59:19 +00001028 SQLITE_UTF8, (void *)(db->pVfs), aFuncs[i].xFunc, 0, 0);
drh7014aff2003-11-01 01:53:53 +00001029 }
danielk1977752e6792004-11-09 16:13:33 +00001030#else
1031 static const struct {
1032 char *zName;
1033 char *zFormat;
1034 } aFuncs[] = {
1035 { "current_time", "%H:%M:%S" },
1036 { "current_date", "%Y-%m-%d" },
1037 { "current_timestamp", "%Y-%m-%d %H:%M:%S" }
1038 };
1039 int i;
1040
1041 for(i=0; i<sizeof(aFuncs)/sizeof(aFuncs[0]); i++){
danielk1977771151b2006-01-17 13:21:40 +00001042 sqlite3CreateFunc(db, aFuncs[i].zName, 0, SQLITE_UTF8,
danielk1977752e6792004-11-09 16:13:33 +00001043 aFuncs[i].zFormat, currentTimeFunc, 0, 0);
1044 }
drhfd1f3942004-07-20 00:39:14 +00001045#endif
drh7014aff2003-11-01 01:53:53 +00001046}