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.
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
28 ** 1970-01-01 00:00:00 is JD 2440587.5
29 ** 2000-01-01 00:00:00 is JD 2451544.5
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
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.
41 ** The conversion algorithms are implemented based on descriptions
42 ** in the following text:
45 ** Astronomical Algorithms, 2nd Edition, 1998
48 ** Richmond, Virginia (USA)
50 #include "sqliteInt.h"
57 #ifndef SQLITE_OMIT_DATETIME_FUNCS
60 ** A structure for holding a single date and time.
62 typedef struct DateTime 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 */
77 ** Convert zDate into one or more integers. Additional arguments
78 ** come in groups of 5 as follows:
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.
86 ** Conversions continue until one with nextC==0 is encountered.
87 ** The function returns the number of successful conversions.
89 static int getDigits(const char *zDate
, ...){
101 min
= va_arg(ap
, int);
102 max
= va_arg(ap
, int);
103 nextC
= va_arg(ap
, int);
104 pVal
= va_arg(ap
, int*);
107 if( !isdigit(*(u8
*)zDate
) ){
110 val
= val
*10 + *zDate
- '0';
113 if( val
<min
|| val
>max
|| (nextC
!=0 && nextC
!=*zDate
) ){
124 ** Read text from z[] and convert into a floating point number. Return
125 ** the number of digits converted.
127 static int getValue(const char *z
, double *pR
){
129 *pR
= sqlite3AtoF(z
, &zEnd
);
134 ** Parse a timezone extension on the end of a date-time.
135 ** The extension is of the form:
139 ** If the parse is successful, write the number of minutes
140 ** of change in *pnMin and return 0. If a parser error occurs,
143 ** A missing specifier is not considered an error.
145 static int parseTimezone(const char *zDate
, DateTime
*p
){
148 while( isspace(*(u8
*)zDate
) ){ zDate
++; }
152 }else if( *zDate
=='+' ){
158 if( getDigits(zDate
, 2, 0, 14, ':', &nHr
, 2, 0, 59, 0, &nMn
)!=2 ){
162 p
->tz
= sgn
*(nMn
+ nHr
*60);
163 while( isspace(*(u8
*)zDate
) ){ zDate
++; }
168 ** Parse times of the form HH:MM or HH:MM:SS or HH:MM:SS.FFFF.
169 ** The HH, MM, and SS must each be exactly 2 digits. The
170 ** fractional seconds FFFF can be one or more digits.
172 ** Return 1 if there is a parsing error and 0 on success.
174 static int parseHhMmSs(const char *zDate
, DateTime
*p
){
177 if( getDigits(zDate
, 2, 0, 24, ':', &h
, 2, 0, 59, 0, &m
)!=2 ){
183 if( getDigits(zDate
, 2, 0, 59, 0, &s
)!=1 ){
187 if( *zDate
=='.' && isdigit((u8
)zDate
[1]) ){
190 while( isdigit(*(u8
*)zDate
) ){
191 ms
= ms
*10.0 + *zDate
- '0';
205 if( parseTimezone(zDate
, p
) ) return 1;
206 p
->validTZ
= p
->tz
!=0;
211 ** Convert from YYYY-MM-DD HH:MM:SS to julian day. We always assume
212 ** that the YYYY-MM-DD is according to the Gregorian calendar.
214 ** Reference: Meeus page 61
216 static void computeJD(DateTime
*p
){
217 int Y
, M
, D
, A
, B
, X1
, X2
;
219 if( p
->validJD
) return;
225 Y
= 2000; /* If no YMD specified, assume 2000-Jan-01 */
235 X1
= 365.25*(Y
+4716);
237 p
->rJD
= X1
+ X2
+ D
+ B
- 1524.5;
241 p
->rJD
+= (p
->h
*3600.0 + p
->m
*60.0 + p
->s
)/86400.0;
243 p
->rJD
+= p
->tz
*60/86400.0;
251 ** Parse dates of the form
253 ** YYYY-MM-DD HH:MM:SS.FFF
254 ** YYYY-MM-DD HH:MM:SS
258 ** Write the result into the DateTime structure and return 0
259 ** on success and 1 if the input string is not a well-formed
262 static int parseYyyyMmDd(const char *zDate
, DateTime
*p
){
271 if( getDigits(zDate
,4,0,9999,'-',&Y
,2,1,12,'-',&M
,2,1,31,0,&D
)!=3 ){
275 while( isspace(*(u8
*)zDate
) || 'T'==*(u8
*)zDate
){ zDate
++; }
276 if( parseHhMmSs(zDate
, p
)==0 ){
277 /* We got the time */
278 }else if( *zDate
==0 ){
295 ** Attempt to parse the given string into a Julian Day Number. Return
296 ** the number of errors.
298 ** The following are acceptable forms for the input string:
300 ** YYYY-MM-DD HH:MM:SS.FFF +/-HH:MM
304 ** In the first form, the +/-HH:MM is always optional. The fractional
305 ** seconds extension (the ".FFF") is optional. The seconds portion
306 ** (":SS.FFF") is option. The year and date can be omitted as long
307 ** as there is a time string. The time string can be omitted as long
308 ** as there is a year and date.
310 static int parseDateOrTime(const char *zDate
, DateTime
*p
){
311 memset(p
, 0, sizeof(*p
));
312 if( parseYyyyMmDd(zDate
,p
)==0 ){
314 }else if( parseHhMmSs(zDate
, p
)==0 ){
316 }else if( sqlite3StrICmp(zDate
,"now")==0){
318 sqlite3OsCurrentTime(&r
);
322 }else if( sqlite3IsNumber(zDate
, 0, SQLITE_UTF8
) ){
323 p
->rJD
= sqlite3AtoF(zDate
, 0);
331 ** Compute the Year, Month, and Day from the julian day number.
333 static void computeYMD(DateTime
*p
){
334 int Z
, A
, B
, C
, D
, E
, X1
;
335 if( p
->validYMD
) return;
342 A
= (Z
- 1867216.25)/36524.25;
343 A
= Z
+ 1 + A
- (A
/4);
345 C
= (B
- 122.1)/365.25;
350 p
->M
= E
<14 ? E
-1 : E
-13;
351 p
->Y
= p
->M
>2 ? C
- 4716 : C
- 4715;
357 ** Compute the Hour, Minute, and Seconds from the julian day number.
359 static void computeHMS(DateTime
*p
){
361 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
){
401 if( x
.Y
<1971 || x
.Y
>=2038 ){
415 t
= (x
.rJD
-2440587.5)*86400.0 + 0.5;
416 sqlite3OsEnterMutex();
418 y
.Y
= pTm
->tm_year
+ 1900;
419 y
.M
= pTm
->tm_mon
+ 1;
424 sqlite3OsLeaveMutex();
430 return y
.rJD
- x
.rJD
;
434 ** Process a modifier to a date-time stamp. The modifiers are
452 ** Return 0 on success and 1 if there is any kind of error.
454 static int parseModifier(const char *zMod
, DateTime
*p
){
460 for(n
=0; n
<sizeof(zBuf
)-1 && zMod
[n
]; n
++){
461 z
[n
] = tolower(zMod
[n
]);
468 ** Assuming the current time value is UTC (a.k.a. GMT), shift it to
471 if( strcmp(z
, "localtime")==0 ){
473 p
->rJD
+= localtimeOffset(p
);
483 ** Treat the current value of p->rJD as the number of
484 ** seconds since 1970. Convert to a real julian day number.
486 if( strcmp(z
, "unixepoch")==0 && p
->validJD
){
487 p
->rJD
= p
->rJD
/86400.0 + 2440587.5;
490 }else if( strcmp(z
, "utc")==0 ){
493 c1
= localtimeOffset(p
);
496 p
->rJD
+= c1
- localtimeOffset(p
);
505 ** Move the date to the same time on the next occurrence of
506 ** weekday N where 0==Sunday, 1==Monday, and so forth. If the
507 ** date is already on the appropriate weekday, this is a no-op.
509 if( strncmp(z
, "weekday ", 8)==0 && getValue(&z
[8],&r
)>0
510 && (n
=r
)==r
&& n
>=0 && r
<7 ){
529 ** Move the date backwards to the beginning of the current day,
532 if( strncmp(z
, "start of ", 9)!=0 ) break;
540 if( strcmp(z
,"month")==0 ){
543 }else if( strcmp(z
,"year")==0 ){
548 }else if( strcmp(z
,"day")==0 ){
568 /* A modifier of the form (+|-)HH:MM:SS.FFF adds (or subtracts) the
569 ** specified number of hours, minutes, seconds, and fractional seconds
570 ** to the time. The ".FFF" may be omitted. The ":SS.FFF" may be
576 if( !isdigit(*(u8
*)z2
) ) z2
++;
577 memset(&tx
, 0, sizeof(tx
));
578 if( parseHhMmSs(z2
, &tx
) ) break;
583 if( z
[0]=='-' ) tx
.rJD
= -tx
.rJD
;
591 while( isspace(*(u8
*)z
) ) z
++;
593 if( n
>10 || n
<3 ) break;
594 if( z
[n
-1]=='s' ){ z
[n
-1] = 0; n
--; }
597 if( n
==3 && strcmp(z
,"day")==0 ){
599 }else if( n
==4 && strcmp(z
,"hour")==0 ){
601 }else if( n
==6 && strcmp(z
,"minute")==0 ){
602 p
->rJD
+= r
/(24.0*60.0);
603 }else if( n
==6 && strcmp(z
,"second")==0 ){
604 p
->rJD
+= r
/(24.0*60.0*60.0);
605 }else if( n
==5 && strcmp(z
,"month")==0 ){
609 x
= p
->M
>0 ? (p
->M
-1)/12 : (p
->M
-12)/12;
616 p
->rJD
+= (r
- y
)*30.0;
618 }else if( n
==4 && strcmp(z
,"year")==0 ){
637 ** Process time function arguments. argv[0] is a date-time stamp.
638 ** argv[1] and following are modifiers. Parse them all and write
639 ** the resulting time into the DateTime structure p. Return 0
640 ** on success and 1 if there are any errors.
642 static int isDate(int argc
, sqlite3_value
**argv
, DateTime
*p
){
644 if( argc
==0 ) return 1;
645 if( SQLITE_NULL
==sqlite3_value_type(argv
[0]) ||
646 parseDateOrTime(sqlite3_value_text(argv
[0]), p
) ) return 1;
647 for(i
=1; i
<argc
; i
++){
648 if( SQLITE_NULL
==sqlite3_value_type(argv
[i
]) ||
649 parseModifier(sqlite3_value_text(argv
[i
]), p
) ) return 1;
656 ** The following routines implement the various date and time functions
661 ** julianday( TIMESTRING, MOD, MOD, ...)
663 ** Return the julian day number of the date specified in the arguments
665 static void juliandayFunc(
666 sqlite3_context
*context
,
671 if( isDate(argc
, argv
, &x
)==0 ){
673 sqlite3_result_double(context
, x
.rJD
);
678 ** datetime( TIMESTRING, MOD, MOD, ...)
680 ** Return YYYY-MM-DD HH:MM:SS
682 static void datetimeFunc(
683 sqlite3_context
*context
,
688 if( isDate(argc
, argv
, &x
)==0 ){
691 sprintf(zBuf
, "%04d-%02d-%02d %02d:%02d:%02d",x
.Y
, x
.M
, x
.D
, x
.h
, x
.m
,
693 sqlite3_result_text(context
, zBuf
, -1, SQLITE_TRANSIENT
);
698 ** time( TIMESTRING, MOD, MOD, ...)
702 static void timeFunc(
703 sqlite3_context
*context
,
708 if( isDate(argc
, argv
, &x
)==0 ){
711 sprintf(zBuf
, "%02d:%02d:%02d", x
.h
, x
.m
, (int)x
.s
);
712 sqlite3_result_text(context
, zBuf
, -1, SQLITE_TRANSIENT
);
717 ** date( TIMESTRING, MOD, MOD, ...)
721 static void dateFunc(
722 sqlite3_context
*context
,
727 if( isDate(argc
, argv
, &x
)==0 ){
730 sprintf(zBuf
, "%04d-%02d-%02d", x
.Y
, x
.M
, x
.D
);
731 sqlite3_result_text(context
, zBuf
, -1, SQLITE_TRANSIENT
);
736 ** strftime( FORMAT, TIMESTRING, MOD, MOD, ...)
738 ** Return a string described by FORMAT. Conversions as follows:
741 ** %f ** fractional seconds SS.SSS
743 ** %j day of year 000-366
744 ** %J ** Julian day number
747 ** %s seconds since 1970-01-01
749 ** %w day of week 0-6 sunday==0
750 ** %W week of year 00-53
754 static void strftimeFunc(
755 sqlite3_context
*context
,
762 const char *zFmt
= sqlite3_value_text(argv
[0]);
764 if( zFmt
==0 || isDate(argc
-1, argv
+1, &x
) ) return;
765 for(i
=0, n
=1; zFmt
[i
]; i
++, n
++){
793 return; /* ERROR. return a NULL */
798 if( n
<sizeof(zBuf
) ){
801 z
= sqliteMalloc( n
);
806 for(i
=j
=0; zFmt
[i
]; i
++){
812 case 'd': sprintf(&z
[j
],"%02d",x
.D
); j
+=2; break;
815 int ms
= (x
.s
- s
)*1000.0;
816 sprintf(&z
[j
],"%02d.%03d",s
,ms
);
820 case 'H': sprintf(&z
[j
],"%02d",x
.h
); j
+=2; break;
821 case 'W': /* Fall thru */
823 int n
; /* Number of days since 1st day of year */
831 int wd
; /* 0=Monday, 1=Tuesday, ... 6=Sunday */
832 wd
= ((int)(x
.rJD
+0.5)) % 7;
833 sprintf(&z
[j
],"%02d",(n
+7-wd
)/7);
836 sprintf(&z
[j
],"%03d",n
+1);
841 case 'J': sprintf(&z
[j
],"%.16g",x
.rJD
); j
+=strlen(&z
[j
]); break;
842 case 'm': sprintf(&z
[j
],"%02d",x
.M
); j
+=2; break;
843 case 'M': sprintf(&z
[j
],"%02d",x
.m
); j
+=2; break;
845 sprintf(&z
[j
],"%d",(int)((x
.rJD
-2440587.5)*86400.0 + 0.5));
849 case 'S': sprintf(&z
[j
],"%02d",(int)(x
.s
+0.5)); j
+=2; break;
850 case 'w': z
[j
++] = (((int)(x
.rJD
+1.5)) % 7) + '0'; break;
851 case 'Y': sprintf(&z
[j
],"%04d",x
.Y
); j
+=strlen(&z
[j
]); break;
852 case '%': z
[j
++] = '%'; break;
857 sqlite3_result_text(context
, z
, -1, SQLITE_TRANSIENT
);
866 ** This function returns the same value as time('now').
868 static void ctimeFunc(
869 sqlite3_context
*context
,
873 sqlite3_value
*pVal
= sqlite3ValueNew();
875 sqlite3ValueSetStr(pVal
, -1, "now", SQLITE_UTF8
, SQLITE_STATIC
);
876 timeFunc(context
, 1, &pVal
);
877 sqlite3ValueFree(pVal
);
884 ** This function returns the same value as date('now').
886 static void cdateFunc(
887 sqlite3_context
*context
,
891 sqlite3_value
*pVal
= sqlite3ValueNew();
893 sqlite3ValueSetStr(pVal
, -1, "now", SQLITE_UTF8
, SQLITE_STATIC
);
894 dateFunc(context
, 1, &pVal
);
895 sqlite3ValueFree(pVal
);
900 ** current_timestamp()
902 ** This function returns the same value as datetime('now').
904 static void ctimestampFunc(
905 sqlite3_context
*context
,
909 sqlite3_value
*pVal
= sqlite3ValueNew();
911 sqlite3ValueSetStr(pVal
, -1, "now", SQLITE_UTF8
, SQLITE_STATIC
);
912 datetimeFunc(context
, 1, &pVal
);
913 sqlite3ValueFree(pVal
);
916 #endif /* !defined(SQLITE_OMIT_DATETIME_FUNCS) */
918 #ifdef SQLITE_OMIT_DATETIME_FUNCS
920 ** If the library is compiled to omit the full-scale date and time
921 ** handling (to get a smaller binary), the following minimal version
922 ** of the functions current_time(), current_date() and current_timestamp()
923 ** are included instead. This is to support column declarations that
924 ** include "DEFAULT CURRENT_TIME" etc.
926 ** This function uses the C-library functions time(), gmtime()
927 ** and strftime(). The format string to pass to strftime() is supplied
928 ** as the user-data for the function.
930 static void currentTimeFunc(
931 sqlite3_context
*context
,
936 char *zFormat
= (char *)sqlite3_user_data(context
);
942 extern int sqlite3_current_time
; /* See os_XXX.c */
943 if( sqlite3_current_time
){
944 t
= sqlite3_current_time
;
949 sqlite3OsEnterMutex();
950 strftime(zBuf
, 20, zFormat
, gmtime(&t
));
951 sqlite3OsLeaveMutex();
953 sqlite3_result_text(context
, zBuf
, -1, SQLITE_TRANSIENT
);
958 ** This function registered all of the above C functions as SQL
959 ** functions. This should be the only routine in this file with
962 void sqlite3RegisterDateTimeFunctions(sqlite3
*db
){
963 #ifndef SQLITE_OMIT_DATETIME_FUNCS
964 static const struct {
967 void (*xFunc
)(sqlite3_context
*,int,sqlite3_value
**);
969 { "julianday", -1, juliandayFunc
},
970 { "date", -1, dateFunc
},
971 { "time", -1, timeFunc
},
972 { "datetime", -1, datetimeFunc
},
973 { "strftime", -1, strftimeFunc
},
974 { "current_time", 0, ctimeFunc
},
975 { "current_timestamp", 0, ctimestampFunc
},
976 { "current_date", 0, cdateFunc
},
980 for(i
=0; i
<sizeof(aFuncs
)/sizeof(aFuncs
[0]); i
++){
981 sqlite3_create_function(db
, aFuncs
[i
].zName
, aFuncs
[i
].nArg
,
982 SQLITE_UTF8
, 0, aFuncs
[i
].xFunc
, 0, 0);
985 static const struct {
989 { "current_time", "%H:%M:%S" },
990 { "current_date", "%Y-%m-%d" },
991 { "current_timestamp", "%Y-%m-%d %H:%M:%S" }
995 for(i
=0; i
<sizeof(aFuncs
)/sizeof(aFuncs
[0]); i
++){
996 sqlite3_create_function(db
, aFuncs
[i
].zName
, 0, SQLITE_UTF8
,
997 aFuncs
[i
].zFormat
, currentTimeFunc
, 0, 0);