blob: 67d08a09ad148d784b766cc51f0002ca3a523336 [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**
drhb1f1e6e2006-09-25 18:01:31 +000019** $Id: date.c,v 1.57 2006/09/25 18:01:32 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) ){
drh029b44b2006-01-15 00:13:15 +0000108 goto end_getDigits;
drheb9a9e82004-02-22 17:49:32 +0000109 }
110 val = val*10 + *zDate - '0';
111 zDate++;
112 }
113 if( val<min || val>max || (nextC!=0 && nextC!=*zDate) ){
drh029b44b2006-01-15 00:13:15 +0000114 goto end_getDigits;
drheb9a9e82004-02-22 17:49:32 +0000115 }
116 *pVal = val;
drh7014aff2003-11-01 01:53:53 +0000117 zDate++;
drheb9a9e82004-02-22 17:49:32 +0000118 cnt++;
119 }while( nextC );
drh029b44b2006-01-15 00:13:15 +0000120end_getDigits:
drh15b9a152006-01-31 20:49:13 +0000121 va_end(ap);
drheb9a9e82004-02-22 17:49:32 +0000122 return cnt;
drh7014aff2003-11-01 01:53:53 +0000123}
124
125/*
126** Read text from z[] and convert into a floating point number. Return
127** the number of digits converted.
128*/
drh487e2622005-06-25 18:42:14 +0000129#define getValue sqlite3AtoF
drh7014aff2003-11-01 01:53:53 +0000130
131/*
132** Parse a timezone extension on the end of a date-time.
133** The extension is of the form:
134**
135** (+/-)HH:MM
136**
137** If the parse is successful, write the number of minutes
138** of change in *pnMin and return 0. If a parser error occurs,
139** return 0.
140**
141** A missing specifier is not considered an error.
142*/
143static int parseTimezone(const char *zDate, DateTime *p){
144 int sgn = 0;
145 int nHr, nMn;
drh4c755c02004-08-08 20:22:17 +0000146 while( isspace(*(u8*)zDate) ){ zDate++; }
drh7014aff2003-11-01 01:53:53 +0000147 p->tz = 0;
148 if( *zDate=='-' ){
149 sgn = -1;
150 }else if( *zDate=='+' ){
151 sgn = +1;
152 }else{
153 return *zDate!=0;
154 }
155 zDate++;
drheb9a9e82004-02-22 17:49:32 +0000156 if( getDigits(zDate, 2, 0, 14, ':', &nHr, 2, 0, 59, 0, &nMn)!=2 ){
157 return 1;
158 }
159 zDate += 5;
drh7014aff2003-11-01 01:53:53 +0000160 p->tz = sgn*(nMn + nHr*60);
drh4c755c02004-08-08 20:22:17 +0000161 while( isspace(*(u8*)zDate) ){ zDate++; }
drh7014aff2003-11-01 01:53:53 +0000162 return *zDate!=0;
163}
164
165/*
166** Parse times of the form HH:MM or HH:MM:SS or HH:MM:SS.FFFF.
167** The HH, MM, and SS must each be exactly 2 digits. The
168** fractional seconds FFFF can be one or more digits.
169**
170** Return 1 if there is a parsing error and 0 on success.
171*/
172static int parseHhMmSs(const char *zDate, DateTime *p){
173 int h, m, s;
174 double ms = 0.0;
drheb9a9e82004-02-22 17:49:32 +0000175 if( getDigits(zDate, 2, 0, 24, ':', &h, 2, 0, 59, 0, &m)!=2 ){
176 return 1;
177 }
178 zDate += 5;
drh7014aff2003-11-01 01:53:53 +0000179 if( *zDate==':' ){
drheb9a9e82004-02-22 17:49:32 +0000180 zDate++;
181 if( getDigits(zDate, 2, 0, 59, 0, &s)!=1 ){
182 return 1;
183 }
184 zDate += 2;
drh4c755c02004-08-08 20:22:17 +0000185 if( *zDate=='.' && isdigit((u8)zDate[1]) ){
drh7014aff2003-11-01 01:53:53 +0000186 double rScale = 1.0;
187 zDate++;
drh4c755c02004-08-08 20:22:17 +0000188 while( isdigit(*(u8*)zDate) ){
drh7014aff2003-11-01 01:53:53 +0000189 ms = ms*10.0 + *zDate - '0';
190 rScale *= 10.0;
191 zDate++;
192 }
193 ms /= rScale;
194 }
195 }else{
196 s = 0;
197 }
198 p->validJD = 0;
199 p->validHMS = 1;
200 p->h = h;
201 p->m = m;
202 p->s = s + ms;
203 if( parseTimezone(zDate, p) ) return 1;
204 p->validTZ = p->tz!=0;
205 return 0;
206}
207
208/*
209** Convert from YYYY-MM-DD HH:MM:SS to julian day. We always assume
210** that the YYYY-MM-DD is according to the Gregorian calendar.
211**
212** Reference: Meeus page 61
213*/
214static void computeJD(DateTime *p){
215 int Y, M, D, A, B, X1, X2;
216
217 if( p->validJD ) return;
218 if( p->validYMD ){
219 Y = p->Y;
220 M = p->M;
221 D = p->D;
222 }else{
drhba212562004-01-08 02:17:31 +0000223 Y = 2000; /* If no YMD specified, assume 2000-Jan-01 */
drh7014aff2003-11-01 01:53:53 +0000224 M = 1;
225 D = 1;
226 }
227 if( M<=2 ){
228 Y--;
229 M += 12;
230 }
231 A = Y/100;
232 B = 2 - A + (A/4);
233 X1 = 365.25*(Y+4716);
234 X2 = 30.6001*(M+1);
235 p->rJD = X1 + X2 + D + B - 1524.5;
236 p->validJD = 1;
drh7014aff2003-11-01 01:53:53 +0000237 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;
drhf11c34d2006-09-08 12:27:36 +0000241 p->validYMD = 0;
drh7014aff2003-11-01 01:53:53 +0000242 p->validHMS = 0;
243 p->validTZ = 0;
244 }
245 }
246}
247
248/*
249** Parse dates of the form
250**
251** YYYY-MM-DD HH:MM:SS.FFF
252** YYYY-MM-DD HH:MM:SS
253** YYYY-MM-DD HH:MM
254** YYYY-MM-DD
255**
256** Write the result into the DateTime structure and return 0
257** on success and 1 if the input string is not a well-formed
258** date.
259*/
260static int parseYyyyMmDd(const char *zDate, DateTime *p){
drh8eb2cce2004-02-21 03:28:18 +0000261 int Y, M, D, neg;
drh7014aff2003-11-01 01:53:53 +0000262
drh8eb2cce2004-02-21 03:28:18 +0000263 if( zDate[0]=='-' ){
264 zDate++;
265 neg = 1;
266 }else{
267 neg = 0;
268 }
drheb9a9e82004-02-22 17:49:32 +0000269 if( getDigits(zDate,4,0,9999,'-',&Y,2,1,12,'-',&M,2,1,31,0,&D)!=3 ){
270 return 1;
271 }
272 zDate += 10;
drh4cb29b42005-03-21 00:43:44 +0000273 while( isspace(*(u8*)zDate) || 'T'==*(u8*)zDate ){ zDate++; }
drheb9a9e82004-02-22 17:49:32 +0000274 if( parseHhMmSs(zDate, p)==0 ){
275 /* We got the time */
drh7014aff2003-11-01 01:53:53 +0000276 }else if( *zDate==0 ){
277 p->validHMS = 0;
278 }else{
279 return 1;
280 }
281 p->validJD = 0;
282 p->validYMD = 1;
drh8eb2cce2004-02-21 03:28:18 +0000283 p->Y = neg ? -Y : Y;
drh7014aff2003-11-01 01:53:53 +0000284 p->M = M;
285 p->D = D;
286 if( p->validTZ ){
287 computeJD(p);
288 }
289 return 0;
290}
291
292/*
293** Attempt to parse the given string into a Julian Day Number. Return
294** the number of errors.
295**
296** The following are acceptable forms for the input string:
297**
298** YYYY-MM-DD HH:MM:SS.FFF +/-HH:MM
299** DDDD.DD
300** now
301**
302** In the first form, the +/-HH:MM is always optional. The fractional
303** seconds extension (the ".FFF") is optional. The seconds portion
304** (":SS.FFF") is option. The year and date can be omitted as long
305** as there is a time string. The time string can be omitted as long
306** as there is a year and date.
307*/
308static int parseDateOrTime(const char *zDate, DateTime *p){
drh7014aff2003-11-01 01:53:53 +0000309 memset(p, 0, sizeof(*p));
drh8eb2cce2004-02-21 03:28:18 +0000310 if( parseYyyyMmDd(zDate,p)==0 ){
drh7014aff2003-11-01 01:53:53 +0000311 return 0;
drh8eb2cce2004-02-21 03:28:18 +0000312 }else if( parseHhMmSs(zDate, p)==0 ){
313 return 0;
danielk19774adee202004-05-08 08:23:19 +0000314 }else if( sqlite3StrICmp(zDate,"now")==0){
drh7014aff2003-11-01 01:53:53 +0000315 double r;
drh66560ad2006-01-06 14:32:19 +0000316 sqlite3OsCurrentTime(&r);
drh018d1a42005-01-15 01:52:31 +0000317 p->rJD = r;
318 p->validJD = 1;
319 return 0;
danielk1977dc8453f2004-06-12 00:42:34 +0000320 }else if( sqlite3IsNumber(zDate, 0, SQLITE_UTF8) ){
drh487e2622005-06-25 18:42:14 +0000321 getValue(zDate, &p->rJD);
drh7014aff2003-11-01 01:53:53 +0000322 p->validJD = 1;
323 return 0;
324 }
325 return 1;
326}
327
328/*
329** Compute the Year, Month, and Day from the julian day number.
330*/
331static void computeYMD(DateTime *p){
332 int Z, A, B, C, D, E, X1;
333 if( p->validYMD ) return;
drh33a9ad22004-02-29 00:40:32 +0000334 if( !p->validJD ){
335 p->Y = 2000;
336 p->M = 1;
337 p->D = 1;
338 }else{
339 Z = p->rJD + 0.5;
340 A = (Z - 1867216.25)/36524.25;
341 A = Z + 1 + A - (A/4);
342 B = A + 1524;
343 C = (B - 122.1)/365.25;
344 D = 365.25*C;
345 E = (B-D)/30.6001;
346 X1 = 30.6001*E;
347 p->D = B - D - X1;
348 p->M = E<14 ? E-1 : E-13;
349 p->Y = p->M>2 ? C - 4716 : C - 4715;
350 }
drh7014aff2003-11-01 01:53:53 +0000351 p->validYMD = 1;
352}
353
354/*
355** Compute the Hour, Minute, and Seconds from the julian day number.
356*/
357static void computeHMS(DateTime *p){
358 int Z, s;
359 if( p->validHMS ) return;
drhf11c34d2006-09-08 12:27:36 +0000360 computeJD(p);
drh7014aff2003-11-01 01:53:53 +0000361 Z = p->rJD + 0.5;
362 s = (p->rJD + 0.5 - Z)*86400000.0 + 0.5;
363 p->s = 0.001*s;
364 s = p->s;
365 p->s -= s;
366 p->h = s/3600;
367 s -= p->h*3600;
368 p->m = s/60;
369 p->s += s - p->m*60;
370 p->validHMS = 1;
371}
372
373/*
drhba212562004-01-08 02:17:31 +0000374** Compute both YMD and HMS
375*/
376static void computeYMD_HMS(DateTime *p){
377 computeYMD(p);
378 computeHMS(p);
379}
380
381/*
382** Clear the YMD and HMS and the TZ
383*/
384static void clearYMD_HMS_TZ(DateTime *p){
385 p->validYMD = 0;
386 p->validHMS = 0;
387 p->validTZ = 0;
388}
389
390/*
drh7091cb02003-12-23 16:22:18 +0000391** Compute the difference (in days) between localtime and UTC (a.k.a. GMT)
392** for the time value p where p is in UTC.
393*/
394static double localtimeOffset(DateTime *p){
395 DateTime x, y;
396 time_t t;
drh7091cb02003-12-23 16:22:18 +0000397 x = *p;
drhba212562004-01-08 02:17:31 +0000398 computeYMD_HMS(&x);
drh7091cb02003-12-23 16:22:18 +0000399 if( x.Y<1971 || x.Y>=2038 ){
400 x.Y = 2000;
401 x.M = 1;
402 x.D = 1;
403 x.h = 0;
404 x.m = 0;
405 x.s = 0.0;
406 } else {
407 int s = x.s + 0.5;
408 x.s = s;
409 }
410 x.tz = 0;
411 x.validJD = 0;
412 computeJD(&x);
413 t = (x.rJD-2440587.5)*86400.0 + 0.5;
drh87595762006-09-08 12:49:43 +0000414#ifdef HAVE_LOCALTIME_R
415 {
416 struct tm sLocal;
417 localtime_r(&t, &sLocal);
418 y.Y = sLocal.tm_year + 1900;
419 y.M = sLocal.tm_mon + 1;
420 y.D = sLocal.tm_mday;
421 y.h = sLocal.tm_hour;
422 y.m = sLocal.tm_min;
423 y.s = sLocal.tm_sec;
424 }
425#else
426 {
427 struct tm *pTm;
428 sqlite3OsEnterMutex();
429 pTm = localtime(&t);
430 y.Y = pTm->tm_year + 1900;
431 y.M = pTm->tm_mon + 1;
432 y.D = pTm->tm_mday;
433 y.h = pTm->tm_hour;
434 y.m = pTm->tm_min;
435 y.s = pTm->tm_sec;
436 sqlite3OsLeaveMutex();
437 }
438#endif
drh7091cb02003-12-23 16:22:18 +0000439 y.validYMD = 1;
440 y.validHMS = 1;
441 y.validJD = 0;
442 y.validTZ = 0;
443 computeJD(&y);
drh7091cb02003-12-23 16:22:18 +0000444 return y.rJD - x.rJD;
445}
446
447/*
drh7014aff2003-11-01 01:53:53 +0000448** Process a modifier to a date-time stamp. The modifiers are
449** as follows:
450**
451** NNN days
452** NNN hours
453** NNN minutes
454** NNN.NNNN seconds
455** NNN months
456** NNN years
457** start of month
458** start of year
459** start of week
460** start of day
461** weekday N
462** unixepoch
drh7091cb02003-12-23 16:22:18 +0000463** localtime
464** utc
drh7014aff2003-11-01 01:53:53 +0000465**
466** Return 0 on success and 1 if there is any kind of error.
467*/
468static int parseModifier(const char *zMod, DateTime *p){
469 int rc = 1;
470 int n;
471 double r;
drh4d5b8362004-01-17 01:16:21 +0000472 char *z, zBuf[30];
473 z = zBuf;
474 for(n=0; n<sizeof(zBuf)-1 && zMod[n]; n++){
drh7014aff2003-11-01 01:53:53 +0000475 z[n] = tolower(zMod[n]);
476 }
477 z[n] = 0;
478 switch( z[0] ){
drh7091cb02003-12-23 16:22:18 +0000479 case 'l': {
480 /* localtime
481 **
482 ** Assuming the current time value is UTC (a.k.a. GMT), shift it to
483 ** show local time.
484 */
485 if( strcmp(z, "localtime")==0 ){
486 computeJD(p);
487 p->rJD += localtimeOffset(p);
drhba212562004-01-08 02:17:31 +0000488 clearYMD_HMS_TZ(p);
drh7091cb02003-12-23 16:22:18 +0000489 rc = 0;
490 }
491 break;
492 }
drh7014aff2003-11-01 01:53:53 +0000493 case 'u': {
494 /*
495 ** unixepoch
496 **
497 ** Treat the current value of p->rJD as the number of
498 ** seconds since 1970. Convert to a real julian day number.
499 */
500 if( strcmp(z, "unixepoch")==0 && p->validJD ){
501 p->rJD = p->rJD/86400.0 + 2440587.5;
drhba212562004-01-08 02:17:31 +0000502 clearYMD_HMS_TZ(p);
drh7014aff2003-11-01 01:53:53 +0000503 rc = 0;
drh7091cb02003-12-23 16:22:18 +0000504 }else if( strcmp(z, "utc")==0 ){
505 double c1;
506 computeJD(p);
507 c1 = localtimeOffset(p);
508 p->rJD -= c1;
drhba212562004-01-08 02:17:31 +0000509 clearYMD_HMS_TZ(p);
drh7091cb02003-12-23 16:22:18 +0000510 p->rJD += c1 - localtimeOffset(p);
drh7091cb02003-12-23 16:22:18 +0000511 rc = 0;
drh7014aff2003-11-01 01:53:53 +0000512 }
513 break;
514 }
515 case 'w': {
516 /*
517 ** weekday N
518 **
drh181fc992004-08-17 10:42:54 +0000519 ** Move the date to the same time on the next occurrence of
drh7014aff2003-11-01 01:53:53 +0000520 ** weekday N where 0==Sunday, 1==Monday, and so forth. If the
drhc5dd9fa2004-01-07 03:29:16 +0000521 ** date is already on the appropriate weekday, this is a no-op.
drh7014aff2003-11-01 01:53:53 +0000522 */
523 if( strncmp(z, "weekday ", 8)==0 && getValue(&z[8],&r)>0
524 && (n=r)==r && n>=0 && r<7 ){
525 int Z;
drhba212562004-01-08 02:17:31 +0000526 computeYMD_HMS(p);
drh7014aff2003-11-01 01:53:53 +0000527 p->validTZ = 0;
528 p->validJD = 0;
529 computeJD(p);
530 Z = p->rJD + 1.5;
531 Z %= 7;
532 if( Z>n ) Z -= 7;
533 p->rJD += n - Z;
drhba212562004-01-08 02:17:31 +0000534 clearYMD_HMS_TZ(p);
drh7014aff2003-11-01 01:53:53 +0000535 rc = 0;
536 }
537 break;
538 }
539 case 's': {
540 /*
541 ** start of TTTTT
542 **
543 ** Move the date backwards to the beginning of the current day,
544 ** or month or year.
545 */
546 if( strncmp(z, "start of ", 9)!=0 ) break;
drh4d5b8362004-01-17 01:16:21 +0000547 z += 9;
drh7014aff2003-11-01 01:53:53 +0000548 computeYMD(p);
549 p->validHMS = 1;
550 p->h = p->m = 0;
551 p->s = 0.0;
552 p->validTZ = 0;
553 p->validJD = 0;
drh4d5b8362004-01-17 01:16:21 +0000554 if( strcmp(z,"month")==0 ){
drh7014aff2003-11-01 01:53:53 +0000555 p->D = 1;
556 rc = 0;
drh4d5b8362004-01-17 01:16:21 +0000557 }else if( strcmp(z,"year")==0 ){
drh7014aff2003-11-01 01:53:53 +0000558 computeYMD(p);
559 p->M = 1;
560 p->D = 1;
561 rc = 0;
drh4d5b8362004-01-17 01:16:21 +0000562 }else if( strcmp(z,"day")==0 ){
drh7014aff2003-11-01 01:53:53 +0000563 rc = 0;
564 }
565 break;
566 }
567 case '+':
568 case '-':
569 case '0':
570 case '1':
571 case '2':
572 case '3':
573 case '4':
574 case '5':
575 case '6':
576 case '7':
577 case '8':
578 case '9': {
579 n = getValue(z, &r);
580 if( n<=0 ) break;
drh33a9ad22004-02-29 00:40:32 +0000581 if( z[n]==':' ){
582 /* A modifier of the form (+|-)HH:MM:SS.FFF adds (or subtracts) the
583 ** specified number of hours, minutes, seconds, and fractional seconds
584 ** to the time. The ".FFF" may be omitted. The ":SS.FFF" may be
585 ** omitted.
586 */
587 const char *z2 = z;
588 DateTime tx;
589 int day;
drh4c755c02004-08-08 20:22:17 +0000590 if( !isdigit(*(u8*)z2) ) z2++;
drh33a9ad22004-02-29 00:40:32 +0000591 memset(&tx, 0, sizeof(tx));
592 if( parseHhMmSs(z2, &tx) ) break;
593 computeJD(&tx);
drh0d131ab2004-02-29 01:08:17 +0000594 tx.rJD -= 0.5;
drh33a9ad22004-02-29 00:40:32 +0000595 day = (int)tx.rJD;
drhb6829e92004-02-29 00:50:33 +0000596 tx.rJD -= day;
drhb6829e92004-02-29 00:50:33 +0000597 if( z[0]=='-' ) tx.rJD = -tx.rJD;
drh0d131ab2004-02-29 01:08:17 +0000598 computeJD(p);
599 clearYMD_HMS_TZ(p);
drhf11c34d2006-09-08 12:27:36 +0000600 p->rJD += tx.rJD;
drh33a9ad22004-02-29 00:40:32 +0000601 rc = 0;
602 break;
603 }
drh4d5b8362004-01-17 01:16:21 +0000604 z += n;
drh4c755c02004-08-08 20:22:17 +0000605 while( isspace(*(u8*)z) ) z++;
drh4d5b8362004-01-17 01:16:21 +0000606 n = strlen(z);
drh7014aff2003-11-01 01:53:53 +0000607 if( n>10 || n<3 ) break;
drh7014aff2003-11-01 01:53:53 +0000608 if( z[n-1]=='s' ){ z[n-1] = 0; n--; }
609 computeJD(p);
610 rc = 0;
611 if( n==3 && strcmp(z,"day")==0 ){
612 p->rJD += r;
613 }else if( n==4 && strcmp(z,"hour")==0 ){
drh7014aff2003-11-01 01:53:53 +0000614 p->rJD += r/24.0;
615 }else if( n==6 && strcmp(z,"minute")==0 ){
drh7014aff2003-11-01 01:53:53 +0000616 p->rJD += r/(24.0*60.0);
617 }else if( n==6 && strcmp(z,"second")==0 ){
drh7014aff2003-11-01 01:53:53 +0000618 p->rJD += r/(24.0*60.0*60.0);
619 }else if( n==5 && strcmp(z,"month")==0 ){
620 int x, y;
drhba212562004-01-08 02:17:31 +0000621 computeYMD_HMS(p);
drh7014aff2003-11-01 01:53:53 +0000622 p->M += r;
623 x = p->M>0 ? (p->M-1)/12 : (p->M-12)/12;
624 p->Y += x;
625 p->M -= x*12;
626 p->validJD = 0;
627 computeJD(p);
628 y = r;
629 if( y!=r ){
630 p->rJD += (r - y)*30.0;
631 }
632 }else if( n==4 && strcmp(z,"year")==0 ){
drhba212562004-01-08 02:17:31 +0000633 computeYMD_HMS(p);
drh7014aff2003-11-01 01:53:53 +0000634 p->Y += r;
635 p->validJD = 0;
636 computeJD(p);
637 }else{
638 rc = 1;
639 }
drhba212562004-01-08 02:17:31 +0000640 clearYMD_HMS_TZ(p);
drh7014aff2003-11-01 01:53:53 +0000641 break;
642 }
643 default: {
644 break;
645 }
646 }
647 return rc;
648}
649
650/*
651** Process time function arguments. argv[0] is a date-time stamp.
652** argv[1] and following are modifiers. Parse them all and write
653** the resulting time into the DateTime structure p. Return 0
654** on success and 1 if there are any errors.
655*/
danielk197751ad0ec2004-05-24 12:39:02 +0000656static int isDate(int argc, sqlite3_value **argv, DateTime *p){
drh7014aff2003-11-01 01:53:53 +0000657 int i;
658 if( argc==0 ) return 1;
drh9c054832004-05-31 18:51:57 +0000659 if( SQLITE_NULL==sqlite3_value_type(argv[0]) ||
drh2646da72005-12-09 20:02:05 +0000660 parseDateOrTime((char*)sqlite3_value_text(argv[0]), p) ) return 1;
drh7014aff2003-11-01 01:53:53 +0000661 for(i=1; i<argc; i++){
drh9c054832004-05-31 18:51:57 +0000662 if( SQLITE_NULL==sqlite3_value_type(argv[i]) ||
drh2646da72005-12-09 20:02:05 +0000663 parseModifier((char*)sqlite3_value_text(argv[i]), p) ) return 1;
drh7014aff2003-11-01 01:53:53 +0000664 }
665 return 0;
666}
667
668
669/*
670** The following routines implement the various date and time functions
671** of SQLite.
672*/
673
674/*
675** julianday( TIMESTRING, MOD, MOD, ...)
676**
677** Return the julian day number of the date specified in the arguments
678*/
drhf9b596e2004-05-26 16:54:42 +0000679static void juliandayFunc(
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 computeJD(&x);
danielk19777e18c252004-05-25 11:47:24 +0000687 sqlite3_result_double(context, x.rJD);
drh7014aff2003-11-01 01:53:53 +0000688 }
689}
690
691/*
692** datetime( TIMESTRING, MOD, MOD, ...)
693**
694** Return YYYY-MM-DD HH:MM:SS
695*/
drhf9b596e2004-05-26 16:54:42 +0000696static void datetimeFunc(
697 sqlite3_context *context,
698 int argc,
699 sqlite3_value **argv
700){
drh7014aff2003-11-01 01:53:53 +0000701 DateTime x;
702 if( isDate(argc, argv, &x)==0 ){
703 char zBuf[100];
drhba212562004-01-08 02:17:31 +0000704 computeYMD_HMS(&x);
drh7014aff2003-11-01 01:53:53 +0000705 sprintf(zBuf, "%04d-%02d-%02d %02d:%02d:%02d",x.Y, x.M, x.D, x.h, x.m,
706 (int)(x.s));
danielk1977d8123362004-06-12 09:25:12 +0000707 sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
drh7014aff2003-11-01 01:53:53 +0000708 }
709}
710
711/*
712** time( TIMESTRING, MOD, MOD, ...)
713**
714** Return HH:MM:SS
715*/
drhf9b596e2004-05-26 16:54:42 +0000716static void timeFunc(
717 sqlite3_context *context,
718 int argc,
719 sqlite3_value **argv
720){
drh7014aff2003-11-01 01:53:53 +0000721 DateTime x;
722 if( isDate(argc, argv, &x)==0 ){
723 char zBuf[100];
724 computeHMS(&x);
725 sprintf(zBuf, "%02d:%02d:%02d", x.h, x.m, (int)x.s);
danielk1977d8123362004-06-12 09:25:12 +0000726 sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
drh7014aff2003-11-01 01:53:53 +0000727 }
728}
729
730/*
731** date( TIMESTRING, MOD, MOD, ...)
732**
733** Return YYYY-MM-DD
734*/
drhf9b596e2004-05-26 16:54:42 +0000735static void dateFunc(
736 sqlite3_context *context,
737 int argc,
738 sqlite3_value **argv
739){
drh7014aff2003-11-01 01:53:53 +0000740 DateTime x;
741 if( isDate(argc, argv, &x)==0 ){
742 char zBuf[100];
743 computeYMD(&x);
744 sprintf(zBuf, "%04d-%02d-%02d", x.Y, x.M, x.D);
danielk1977d8123362004-06-12 09:25:12 +0000745 sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
drh7014aff2003-11-01 01:53:53 +0000746 }
747}
748
749/*
750** strftime( FORMAT, TIMESTRING, MOD, MOD, ...)
751**
752** Return a string described by FORMAT. Conversions as follows:
753**
754** %d day of month
755** %f ** fractional seconds SS.SSS
756** %H hour 00-24
757** %j day of year 000-366
758** %J ** Julian day number
759** %m month 01-12
760** %M minute 00-59
761** %s seconds since 1970-01-01
762** %S seconds 00-59
763** %w day of week 0-6 sunday==0
764** %W week of year 00-53
765** %Y year 0000-9999
766** %% %
767*/
drhf9b596e2004-05-26 16:54:42 +0000768static void strftimeFunc(
769 sqlite3_context *context,
770 int argc,
771 sqlite3_value **argv
772){
drh7014aff2003-11-01 01:53:53 +0000773 DateTime x;
774 int n, i, j;
775 char *z;
drh2646da72005-12-09 20:02:05 +0000776 const char *zFmt = (const char*)sqlite3_value_text(argv[0]);
drh7014aff2003-11-01 01:53:53 +0000777 char zBuf[100];
danielk197751ad0ec2004-05-24 12:39:02 +0000778 if( zFmt==0 || isDate(argc-1, argv+1, &x) ) return;
drh7014aff2003-11-01 01:53:53 +0000779 for(i=0, n=1; zFmt[i]; i++, n++){
780 if( zFmt[i]=='%' ){
781 switch( zFmt[i+1] ){
782 case 'd':
783 case 'H':
784 case 'm':
785 case 'M':
786 case 'S':
787 case 'W':
788 n++;
789 /* fall thru */
790 case 'w':
791 case '%':
792 break;
793 case 'f':
794 n += 8;
795 break;
796 case 'j':
797 n += 3;
798 break;
799 case 'Y':
800 n += 8;
801 break;
802 case 's':
803 case 'J':
804 n += 50;
805 break;
806 default:
807 return; /* ERROR. return a NULL */
808 }
809 i++;
810 }
811 }
812 if( n<sizeof(zBuf) ){
813 z = zBuf;
814 }else{
815 z = sqliteMalloc( n );
816 if( z==0 ) return;
817 }
818 computeJD(&x);
drhba212562004-01-08 02:17:31 +0000819 computeYMD_HMS(&x);
drh7014aff2003-11-01 01:53:53 +0000820 for(i=j=0; zFmt[i]; i++){
821 if( zFmt[i]!='%' ){
822 z[j++] = zFmt[i];
823 }else{
824 i++;
825 switch( zFmt[i] ){
826 case 'd': sprintf(&z[j],"%02d",x.D); j+=2; break;
827 case 'f': {
drhb1f1e6e2006-09-25 18:01:31 +0000828 double s = x.s;
829 if( s>59.999 ) s = 59.999;
830 sqlite3_snprintf(7, &z[j],"%02.3f", s);
drh7014aff2003-11-01 01:53:53 +0000831 j += strlen(&z[j]);
832 break;
833 }
834 case 'H': sprintf(&z[j],"%02d",x.h); j+=2; break;
835 case 'W': /* Fall thru */
836 case 'j': {
danielk1977f0113002006-01-24 12:09:17 +0000837 int nDay; /* Number of days since 1st day of year */
drh7014aff2003-11-01 01:53:53 +0000838 DateTime y = x;
839 y.validJD = 0;
840 y.M = 1;
841 y.D = 1;
842 computeJD(&y);
danielk1977f0113002006-01-24 12:09:17 +0000843 nDay = x.rJD - y.rJD;
drh7014aff2003-11-01 01:53:53 +0000844 if( zFmt[i]=='W' ){
drh1020d492004-07-18 22:22:43 +0000845 int wd; /* 0=Monday, 1=Tuesday, ... 6=Sunday */
846 wd = ((int)(x.rJD+0.5)) % 7;
danielk1977f0113002006-01-24 12:09:17 +0000847 sprintf(&z[j],"%02d",(nDay+7-wd)/7);
drh7014aff2003-11-01 01:53:53 +0000848 j += 2;
849 }else{
danielk1977f0113002006-01-24 12:09:17 +0000850 sprintf(&z[j],"%03d",nDay+1);
drh7014aff2003-11-01 01:53:53 +0000851 j += 3;
852 }
853 break;
854 }
855 case 'J': sprintf(&z[j],"%.16g",x.rJD); j+=strlen(&z[j]); break;
856 case 'm': sprintf(&z[j],"%02d",x.M); j+=2; break;
857 case 'M': sprintf(&z[j],"%02d",x.m); j+=2; break;
858 case 's': {
drhc5dd9fa2004-01-07 03:29:16 +0000859 sprintf(&z[j],"%d",(int)((x.rJD-2440587.5)*86400.0 + 0.5));
drh7014aff2003-11-01 01:53:53 +0000860 j += strlen(&z[j]);
861 break;
862 }
drhc5dd9fa2004-01-07 03:29:16 +0000863 case 'S': sprintf(&z[j],"%02d",(int)(x.s+0.5)); j+=2; break;
drh7014aff2003-11-01 01:53:53 +0000864 case 'w': z[j++] = (((int)(x.rJD+1.5)) % 7) + '0'; break;
865 case 'Y': sprintf(&z[j],"%04d",x.Y); j+=strlen(&z[j]); break;
866 case '%': z[j++] = '%'; break;
867 }
868 }
869 }
870 z[j] = 0;
danielk1977d8123362004-06-12 09:25:12 +0000871 sqlite3_result_text(context, z, -1, SQLITE_TRANSIENT);
drh7014aff2003-11-01 01:53:53 +0000872 if( z!=zBuf ){
873 sqliteFree(z);
874 }
875}
876
danielk19777977a172004-11-09 12:44:37 +0000877/*
878** current_time()
879**
880** This function returns the same value as time('now').
881*/
882static void ctimeFunc(
883 sqlite3_context *context,
884 int argc,
885 sqlite3_value **argv
886){
887 sqlite3_value *pVal = sqlite3ValueNew();
888 if( pVal ){
889 sqlite3ValueSetStr(pVal, -1, "now", SQLITE_UTF8, SQLITE_STATIC);
890 timeFunc(context, 1, &pVal);
891 sqlite3ValueFree(pVal);
892 }
893}
drh7014aff2003-11-01 01:53:53 +0000894
danielk19777977a172004-11-09 12:44:37 +0000895/*
896** current_date()
897**
898** This function returns the same value as date('now').
899*/
900static void cdateFunc(
901 sqlite3_context *context,
902 int argc,
903 sqlite3_value **argv
904){
905 sqlite3_value *pVal = sqlite3ValueNew();
906 if( pVal ){
907 sqlite3ValueSetStr(pVal, -1, "now", SQLITE_UTF8, SQLITE_STATIC);
908 dateFunc(context, 1, &pVal);
909 sqlite3ValueFree(pVal);
910 }
911}
912
913/*
914** current_timestamp()
915**
916** This function returns the same value as datetime('now').
917*/
918static void ctimestampFunc(
919 sqlite3_context *context,
920 int argc,
921 sqlite3_value **argv
922){
923 sqlite3_value *pVal = sqlite3ValueNew();
924 if( pVal ){
925 sqlite3ValueSetStr(pVal, -1, "now", SQLITE_UTF8, SQLITE_STATIC);
926 datetimeFunc(context, 1, &pVal);
927 sqlite3ValueFree(pVal);
928 }
929}
drh7014aff2003-11-01 01:53:53 +0000930#endif /* !defined(SQLITE_OMIT_DATETIME_FUNCS) */
931
danielk1977752e6792004-11-09 16:13:33 +0000932#ifdef SQLITE_OMIT_DATETIME_FUNCS
933/*
934** If the library is compiled to omit the full-scale date and time
935** handling (to get a smaller binary), the following minimal version
936** of the functions current_time(), current_date() and current_timestamp()
937** are included instead. This is to support column declarations that
938** include "DEFAULT CURRENT_TIME" etc.
939**
danielk19772df9fab2004-11-11 01:50:30 +0000940** This function uses the C-library functions time(), gmtime()
danielk1977752e6792004-11-09 16:13:33 +0000941** and strftime(). The format string to pass to strftime() is supplied
942** as the user-data for the function.
943*/
danielk1977752e6792004-11-09 16:13:33 +0000944static void currentTimeFunc(
945 sqlite3_context *context,
946 int argc,
947 sqlite3_value **argv
948){
949 time_t t;
950 char *zFormat = (char *)sqlite3_user_data(context);
951 char zBuf[20];
danielk1977752e6792004-11-09 16:13:33 +0000952
danielk1977752e6792004-11-09 16:13:33 +0000953 time(&t);
954#ifdef SQLITE_TEST
drh6c626082004-11-14 21:56:29 +0000955 {
956 extern int sqlite3_current_time; /* See os_XXX.c */
957 if( sqlite3_current_time ){
958 t = sqlite3_current_time;
959 }
danielk1977752e6792004-11-09 16:13:33 +0000960 }
961#endif
danielk1977e6efa742004-11-10 11:55:10 +0000962
drh87595762006-09-08 12:49:43 +0000963#ifdef HAVE_GMTIME_R
964 {
965 struct tm sNow;
966 gmtime_r(&t, &sNow);
967 strftime(zBuf, 20, zFormat, &sNow);
968 }
969#else
970 {
971 struct tm *pTm;
972 sqlite3OsEnterMutex();
973 pTm = gmtime(&t);
974 strftime(zBuf, 20, zFormat, pTm);
975 sqlite3OsLeaveMutex();
976 }
977#endif
danielk1977e6efa742004-11-10 11:55:10 +0000978
danielk1977752e6792004-11-09 16:13:33 +0000979 sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
980}
981#endif
982
drh7014aff2003-11-01 01:53:53 +0000983/*
984** This function registered all of the above C functions as SQL
985** functions. This should be the only routine in this file with
986** external linkage.
987*/
drh9bb575f2004-09-06 17:24:11 +0000988void sqlite3RegisterDateTimeFunctions(sqlite3 *db){
drhfd1f3942004-07-20 00:39:14 +0000989#ifndef SQLITE_OMIT_DATETIME_FUNCS
drh57196282004-10-06 15:41:16 +0000990 static const struct {
drh7014aff2003-11-01 01:53:53 +0000991 char *zName;
992 int nArg;
danielk19770ae8b832004-05-25 12:05:56 +0000993 void (*xFunc)(sqlite3_context*,int,sqlite3_value**);
drh7014aff2003-11-01 01:53:53 +0000994 } aFuncs[] = {
drhf9b596e2004-05-26 16:54:42 +0000995 { "julianday", -1, juliandayFunc },
996 { "date", -1, dateFunc },
997 { "time", -1, timeFunc },
998 { "datetime", -1, datetimeFunc },
999 { "strftime", -1, strftimeFunc },
danielk19777977a172004-11-09 12:44:37 +00001000 { "current_time", 0, ctimeFunc },
1001 { "current_timestamp", 0, ctimestampFunc },
1002 { "current_date", 0, cdateFunc },
drh7014aff2003-11-01 01:53:53 +00001003 };
1004 int i;
1005
1006 for(i=0; i<sizeof(aFuncs)/sizeof(aFuncs[0]); i++){
danielk1977771151b2006-01-17 13:21:40 +00001007 sqlite3CreateFunc(db, aFuncs[i].zName, aFuncs[i].nArg,
danielk1977f9d64d22004-06-19 08:18:07 +00001008 SQLITE_UTF8, 0, aFuncs[i].xFunc, 0, 0);
drh7014aff2003-11-01 01:53:53 +00001009 }
danielk1977752e6792004-11-09 16:13:33 +00001010#else
1011 static const struct {
1012 char *zName;
1013 char *zFormat;
1014 } aFuncs[] = {
1015 { "current_time", "%H:%M:%S" },
1016 { "current_date", "%Y-%m-%d" },
1017 { "current_timestamp", "%Y-%m-%d %H:%M:%S" }
1018 };
1019 int i;
1020
1021 for(i=0; i<sizeof(aFuncs)/sizeof(aFuncs[0]); i++){
danielk1977771151b2006-01-17 13:21:40 +00001022 sqlite3CreateFunc(db, aFuncs[i].zName, 0, SQLITE_UTF8,
danielk1977752e6792004-11-09 16:13:33 +00001023 aFuncs[i].zFormat, currentTimeFunc, 0, 0);
1024 }
drhfd1f3942004-07-20 00:39:14 +00001025#endif
drh7014aff2003-11-01 01:53:53 +00001026}