4 ** The author disclaims copyright to this source code. In place of
5 ** a legal notice, here is a blessing:
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.
11 *************************************************************************
12 ** This file contains the C functions that implement date and time
13 ** functions for SQLite.
15 ** There is only one exported symbol in this file - the function
16 ** sqlite3RegisterDateTimeFunctions() found at the bottom of the file.
17 ** All other code has file scope.
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
26 ** 1970-01-01 00:00:00 is JD 2440587.5
27 ** 2000-01-01 00:00:00 is JD 2451544.5
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
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.
39 ** The conversion algorithms are implemented based on descriptions
40 ** in the following text:
43 ** Astronomical Algorithms, 2nd Edition, 1998
46 ** Richmond, Virginia (USA)
48 #include "sqliteInt.h"
54 #ifndef SQLITE_OMIT_DATETIME_FUNCS
57 ** A structure for holding a single date and time.
59 typedef struct DateTime 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 */
74 ** Convert zDate into one or more integers. Additional arguments
75 ** come in groups of 5 as follows:
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.
83 ** Conversions continue until one with nextC==0 is encountered.
84 ** The function returns the number of successful conversions.
86 static int getDigits(const char *zDate, ...){
98 min = va_arg(ap, int);
99 max = va_arg(ap, int);
100 nextC = va_arg(ap, int);
101 pVal = va_arg(ap, int*);
104 if( !isdigit(*(u8*)zDate) ){
107 val = val*10 + *zDate - '0';
110 if( val<min || val>max || (nextC!=0 && nextC!=*zDate) ){
123 ** Read text from z[] and convert into a floating point number. Return
124 ** the number of digits converted.
126 #define getValue sqlite3AtoF
129 ** Parse a timezone extension on the end of a date-time.
130 ** The extension is of the form:
134 ** If the parse is successful, write the number of minutes
135 ** of change in *pnMin and return 0. If a parser error occurs,
138 ** A missing specifier is not considered an error.
140 static int parseTimezone(const char *zDate, DateTime *p){
143 while( isspace(*(u8*)zDate) ){ zDate++; }
147 }else if( *zDate=='+' ){
153 if( getDigits(zDate, 2, 0, 14, ':', &nHr, 2, 0, 59, 0, &nMn)!=2 ){
157 p->tz = sgn*(nMn + nHr*60);
158 while( isspace(*(u8*)zDate) ){ zDate++; }
163 ** Parse times of the form HH:MM or HH:MM:SS or HH:MM:SS.FFFF.
164 ** The HH, MM, and SS must each be exactly 2 digits. The
165 ** fractional seconds FFFF can be one or more digits.
167 ** Return 1 if there is a parsing error and 0 on success.
169 static int parseHhMmSs(const char *zDate, DateTime *p){
172 if( getDigits(zDate, 2, 0, 24, ':', &h, 2, 0, 59, 0, &m)!=2 ){
178 if( getDigits(zDate, 2, 0, 59, 0, &s)!=1 ){
182 if( *zDate=='.' && isdigit((u8)zDate[1]) ){
185 while( isdigit(*(u8*)zDate) ){
186 ms = ms*10.0 + *zDate - '0';
200 if( parseTimezone(zDate, p) ) return 1;
201 p->validTZ = p->tz!=0;
206 ** Convert from YYYY-MM-DD HH:MM:SS to julian day. We always assume
207 ** that the YYYY-MM-DD is according to the Gregorian calendar.
209 ** Reference: Meeus page 61
211 static void computeJD(DateTime *p){
212 int Y, M, D, A, B, X1, X2;
214 if( p->validJD ) return;
220 Y = 2000; /* If no YMD specified, assume 2000-Jan-01 */
230 X1 = 365.25*(Y+4716);
232 p->rJD = X1 + X2 + D + B - 1524.5;
235 p->rJD += (p->h*3600.0 + p->m*60.0 + p->s)/86400.0;
237 p->rJD -= p->tz*60/86400.0;
246 ** Parse dates of the form
248 ** YYYY-MM-DD HH:MM:SS.FFF
249 ** YYYY-MM-DD HH:MM:SS
253 ** Write the result into the DateTime structure and return 0
254 ** on success and 1 if the input string is not a well-formed
257 static int parseYyyyMmDd(const char *zDate, DateTime *p){
266 if( getDigits(zDate,4,0,9999,'-',&Y,2,1,12,'-',&M,2,1,31,0,&D)!=3 ){
270 while( isspace(*(u8*)zDate) || 'T'==*(u8*)zDate ){ zDate++; }
271 if( parseHhMmSs(zDate, p)==0 ){
272 /* We got the time */
273 }else if( *zDate==0 ){
290 ** Attempt to parse the given string into a Julian Day Number. Return
291 ** the number of errors.
293 ** The following are acceptable forms for the input string:
295 ** YYYY-MM-DD HH:MM:SS.FFF +/-HH:MM
299 ** In the first form, the +/-HH:MM is always optional. The fractional
300 ** seconds extension (the ".FFF") is optional. The seconds portion
301 ** (":SS.FFF") is option. The year and date can be omitted as long
302 ** as there is a time string. The time string can be omitted as long
303 ** as there is a year and date.
305 static int parseDateOrTime(
306 sqlite3_context *context,
310 memset(p, 0, sizeof(*p));
311 if( parseYyyyMmDd(zDate,p)==0 ){
313 }else if( parseHhMmSs(zDate, p)==0 ){
315 }else if( sqlite3StrICmp(zDate,"now")==0){
317 sqlite3OsCurrentTime((sqlite3_vfs *)sqlite3_user_data(context), &r);
321 }else if( sqlite3IsNumber(zDate, 0, SQLITE_UTF8) ){
322 getValue(zDate, &p->rJD);
330 ** Compute the Year, Month, and Day from the julian day number.
332 static void computeYMD(DateTime *p){
333 int Z, A, B, C, D, E, X1;
334 if( p->validYMD ) return;
341 A = (Z - 1867216.25)/36524.25;
342 A = Z + 1 + A - (A/4);
344 C = (B - 122.1)/365.25;
349 p->M = E<14 ? E-1 : E-13;
350 p->Y = p->M>2 ? C - 4716 : C - 4715;
356 ** Compute the Hour, Minute, and Seconds from the julian day number.
358 static void computeHMS(DateTime *p){
360 if( p->validHMS ) return;
363 s = (p->rJD + 0.5 - Z)*86400000.0 + 0.5;
375 ** Compute both YMD and HMS
377 static void computeYMD_HMS(DateTime *p){
383 ** Clear the YMD and HMS and the TZ
385 static void clearYMD_HMS_TZ(DateTime *p){
392 ** Compute the difference (in days) between localtime and UTC (a.k.a. GMT)
393 ** for the time value p where p is in UTC.
395 static double localtimeOffset(DateTime *p){
400 if( x.Y<1971 || x.Y>=2038 ){
414 t = (x.rJD-2440587.5)*86400.0 + 0.5;
415 #ifdef HAVE_LOCALTIME_R
418 localtime_r(&t, &sLocal);
419 y.Y = sLocal.tm_year + 1900;
420 y.M = sLocal.tm_mon + 1;
421 y.D = sLocal.tm_mday;
422 y.h = sLocal.tm_hour;
429 sqlite3_mutex_enter(sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_MASTER));
431 y.Y = pTm->tm_year + 1900;
432 y.M = pTm->tm_mon + 1;
437 sqlite3_mutex_leave(sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_MASTER));
445 return y.rJD - x.rJD;
449 ** Process a modifier to a date-time stamp. The modifiers are
467 ** Return 0 on success and 1 if there is any kind of error.
469 static int parseModifier(const char *zMod, DateTime *p){
475 for(n=0; n<sizeof(zBuf)-1 && zMod[n]; n++){
476 z[n] = tolower(zMod[n]);
483 ** Assuming the current time value is UTC (a.k.a. GMT), shift it to
486 if( strcmp(z, "localtime")==0 ){
488 p->rJD += localtimeOffset(p);
498 ** Treat the current value of p->rJD as the number of
499 ** seconds since 1970. Convert to a real julian day number.
501 if( strcmp(z, "unixepoch")==0 && p->validJD ){
502 p->rJD = p->rJD/86400.0 + 2440587.5;
505 }else if( strcmp(z, "utc")==0 ){
508 c1 = localtimeOffset(p);
511 p->rJD += c1 - localtimeOffset(p);
520 ** Move the date to the same time on the next occurrence of
521 ** weekday N where 0==Sunday, 1==Monday, and so forth. If the
522 ** date is already on the appropriate weekday, this is a no-op.
524 if( strncmp(z, "weekday ", 8)==0 && getValue(&z[8],&r)>0
525 && (n=r)==r && n>=0 && r<7 ){
544 ** Move the date backwards to the beginning of the current day,
547 if( strncmp(z, "start of ", 9)!=0 ) break;
555 if( strcmp(z,"month")==0 ){
558 }else if( strcmp(z,"year")==0 ){
563 }else if( strcmp(z,"day")==0 ){
583 /* A modifier of the form (+|-)HH:MM:SS.FFF adds (or subtracts) the
584 ** specified number of hours, minutes, seconds, and fractional seconds
585 ** to the time. The ".FFF" may be omitted. The ":SS.FFF" may be
591 if( !isdigit(*(u8*)z2) ) z2++;
592 memset(&tx, 0, sizeof(tx));
593 if( parseHhMmSs(z2, &tx) ) break;
598 if( z[0]=='-' ) tx.rJD = -tx.rJD;
606 while( isspace(*(u8*)z) ) z++;
608 if( n>10 || n<3 ) break;
609 if( z[n-1]=='s' ){ z[n-1] = 0; n--; }
612 if( n==3 && strcmp(z,"day")==0 ){
614 }else if( n==4 && strcmp(z,"hour")==0 ){
616 }else if( n==6 && strcmp(z,"minute")==0 ){
617 p->rJD += r/(24.0*60.0);
618 }else if( n==6 && strcmp(z,"second")==0 ){
619 p->rJD += r/(24.0*60.0*60.0);
620 }else if( n==5 && strcmp(z,"month")==0 ){
624 x = p->M>0 ? (p->M-1)/12 : (p->M-12)/12;
631 p->rJD += (r - y)*30.0;
633 }else if( n==4 && strcmp(z,"year")==0 ){
652 ** Process time function arguments. argv[0] is a date-time stamp.
653 ** argv[1] and following are modifiers. Parse them all and write
654 ** the resulting time into the DateTime structure p. Return 0
655 ** on success and 1 if there are any errors.
658 sqlite3_context *context,
660 sqlite3_value **argv,
664 const unsigned char *z;
665 if( argc==0 ) return 1;
666 z = sqlite3_value_text(argv[0]);
667 if( !z || parseDateOrTime(context, (char*)z, p) ){
670 for(i=1; i<argc; i++){
671 if( (z = sqlite3_value_text(argv[i]))==0 || parseModifier((char*)z, p) ){
680 ** The following routines implement the various date and time functions
685 ** julianday( TIMESTRING, MOD, MOD, ...)
687 ** Return the julian day number of the date specified in the arguments
689 static void juliandayFunc(
690 sqlite3_context *context,
695 if( isDate(context, argc, argv, &x)==0 ){
697 sqlite3_result_double(context, x.rJD);
702 ** datetime( TIMESTRING, MOD, MOD, ...)
704 ** Return YYYY-MM-DD HH:MM:SS
706 static void datetimeFunc(
707 sqlite3_context *context,
712 if( isDate(context, argc, argv, &x)==0 ){
715 sqlite3_snprintf(sizeof(zBuf), zBuf, "%04d-%02d-%02d %02d:%02d:%02d",
716 x.Y, x.M, x.D, x.h, x.m, (int)(x.s));
717 sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
722 ** time( TIMESTRING, MOD, MOD, ...)
726 static void timeFunc(
727 sqlite3_context *context,
732 if( isDate(context, argc, argv, &x)==0 ){
735 sqlite3_snprintf(sizeof(zBuf), zBuf, "%02d:%02d:%02d", x.h, x.m, (int)x.s);
736 sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
741 ** date( TIMESTRING, MOD, MOD, ...)
745 static void dateFunc(
746 sqlite3_context *context,
751 if( isDate(context, argc, argv, &x)==0 ){
754 sqlite3_snprintf(sizeof(zBuf), zBuf, "%04d-%02d-%02d", x.Y, x.M, x.D);
755 sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
760 ** strftime( FORMAT, TIMESTRING, MOD, MOD, ...)
762 ** Return a string described by FORMAT. Conversions as follows:
765 ** %f ** fractional seconds SS.SSS
767 ** %j day of year 000-366
768 ** %J ** Julian day number
771 ** %s seconds since 1970-01-01
773 ** %w day of week 0-6 sunday==0
774 ** %W week of year 00-53
778 static void strftimeFunc(
779 sqlite3_context *context,
787 const char *zFmt = (const char*)sqlite3_value_text(argv[0]);
789 if( zFmt==0 || isDate(context, argc-1, argv+1, &x) ) return;
790 for(i=0, n=1; zFmt[i]; i++, n++){
818 return; /* ERROR. return a NULL */
823 if( n<sizeof(zBuf) ){
825 }else if( n>SQLITE_MAX_LENGTH ){
826 sqlite3_result_error_toobig(context);
829 z = sqlite3_malloc( n );
834 for(i=j=0; zFmt[i]; i++){
840 case 'd': sqlite3_snprintf(3, &z[j],"%02d",x.D); j+=2; break;
843 if( s>59.999 ) s = 59.999;
844 sqlite3_snprintf(7, &z[j],"%06.3f", s);
848 case 'H': sqlite3_snprintf(3, &z[j],"%02d",x.h); j+=2; break;
849 case 'W': /* Fall thru */
851 int nDay; /* Number of days since 1st day of year */
857 nDay = x.rJD - y.rJD + 0.5;
859 int wd; /* 0=Monday, 1=Tuesday, ... 6=Sunday */
860 wd = ((int)(x.rJD+0.5)) % 7;
861 sqlite3_snprintf(3, &z[j],"%02d",(nDay+7-wd)/7);
864 sqlite3_snprintf(4, &z[j],"%03d",nDay+1);
870 sqlite3_snprintf(20, &z[j],"%.16g",x.rJD);
874 case 'm': sqlite3_snprintf(3, &z[j],"%02d",x.M); j+=2; break;
875 case 'M': sqlite3_snprintf(3, &z[j],"%02d",x.m); j+=2; break;
877 sqlite3_snprintf(30,&z[j],"%d",
878 (int)((x.rJD-2440587.5)*86400.0 + 0.5));
882 case 'S': sqlite3_snprintf(3,&z[j],"%02d",(int)x.s); j+=2; break;
883 case 'w': z[j++] = (((int)(x.rJD+1.5)) % 7) + '0'; break;
884 case 'Y': sqlite3_snprintf(5,&z[j],"%04d",x.Y); j+=strlen(&z[j]);break;
885 case '%': z[j++] = '%'; break;
890 sqlite3_result_text(context, z, -1, SQLITE_TRANSIENT);
899 ** This function returns the same value as time('now').
901 static void ctimeFunc(
902 sqlite3_context *context,
906 sqlite3_value *pVal = sqlite3ValueNew(0);
908 sqlite3ValueSetStr(pVal, -1, "now", SQLITE_UTF8, SQLITE_STATIC);
909 timeFunc(context, 1, &pVal);
910 sqlite3ValueFree(pVal);
917 ** This function returns the same value as date('now').
919 static void cdateFunc(
920 sqlite3_context *context,
924 sqlite3_value *pVal = sqlite3ValueNew(0);
926 sqlite3ValueSetStr(pVal, -1, "now", SQLITE_UTF8, SQLITE_STATIC);
927 dateFunc(context, 1, &pVal);
928 sqlite3ValueFree(pVal);
933 ** current_timestamp()
935 ** This function returns the same value as datetime('now').
937 static void ctimestampFunc(
938 sqlite3_context *context,
942 sqlite3_value *pVal = sqlite3ValueNew(0);
944 sqlite3ValueSetStr(pVal, -1, "now", SQLITE_UTF8, SQLITE_STATIC);
945 datetimeFunc(context, 1, &pVal);
946 sqlite3ValueFree(pVal);
949 #endif /* !defined(SQLITE_OMIT_DATETIME_FUNCS) */
951 #ifdef SQLITE_OMIT_DATETIME_FUNCS
953 ** If the library is compiled to omit the full-scale date and time
954 ** handling (to get a smaller binary), the following minimal version
955 ** of the functions current_time(), current_date() and current_timestamp()
956 ** are included instead. This is to support column declarations that
957 ** include "DEFAULT CURRENT_TIME" etc.
959 ** This function uses the C-library functions time(), gmtime()
960 ** and strftime(). The format string to pass to strftime() is supplied
961 ** as the user-data for the function.
963 static void currentTimeFunc(
964 sqlite3_context *context,
969 char *zFormat = (char *)sqlite3_user_data(context);
975 extern int sqlite3_current_time; /* See os_XXX.c */
976 if( sqlite3_current_time ){
977 t = sqlite3_current_time;
986 strftime(zBuf, 20, zFormat, &sNow);
991 sqlite3_mutex_enter(sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_MASTER));
993 strftime(zBuf, 20, zFormat, pTm);
994 sqlite3_mutex_leave(sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_MASTER));
998 sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
1003 ** This function registered all of the above C functions as SQL
1004 ** functions. This should be the only routine in this file with
1005 ** external linkage.
1007 void sqlite3RegisterDateTimeFunctions(sqlite3 *db){
1008 #ifndef SQLITE_OMIT_DATETIME_FUNCS
1009 static const struct {
1012 void (*xFunc)(sqlite3_context*,int,sqlite3_value**);
1014 { "julianday", -1, juliandayFunc },
1015 { "date", -1, dateFunc },
1016 { "time", -1, timeFunc },
1017 { "datetime", -1, datetimeFunc },
1018 { "strftime", -1, strftimeFunc },
1019 { "current_time", 0, ctimeFunc },
1020 { "current_timestamp", 0, ctimestampFunc },
1021 { "current_date", 0, cdateFunc },
1025 for(i=0; i<sizeof(aFuncs)/sizeof(aFuncs[0]); i++){
1026 sqlite3CreateFunc(db, aFuncs[i].zName, aFuncs[i].nArg,
1027 SQLITE_UTF8, (void *)(db->pVfs), aFuncs[i].xFunc, 0, 0);
1030 static const struct {
1034 { "current_time", "%H:%M:%S" },
1035 { "current_date", "%Y-%m-%d" },
1036 { "current_timestamp", "%Y-%m-%d %H:%M:%S" }
1040 for(i=0; i<sizeof(aFuncs)/sizeof(aFuncs[0]); i++){
1041 sqlite3CreateFunc(db, aFuncs[i].zName, 0, SQLITE_UTF8,
1042 aFuncs[i].zFormat, currentTimeFunc, 0, 0);