SQLite Forum

Small tweaks for date handling functions
Login

Small tweaks for date handling functions

(1.1) By Nuno Cruces (ncruces) on 2024-01-20 10:31:39 edited from 1.0 [source]

I'd like to propose a few small tweaks of date handling functions. In particular, this patch:

--- a/src/date.c
+++ b/src/date.c
@@ -340,6 +340,7 @@ static int setDateTimeToCurrent(sqlite3_context *context, DateTime *p){
   p->iJD = sqlite3StmtCurrentTime(context);
   if( p->iJD>0 ){
     p->validJD = 1;
+    p->tzSet = 1;
     return 0;
   }else{
     return 1;
@@ -355,6 +356,7 @@ static int setDateTimeToCurrent(sqlite3_context *context, DateTime *p){
 static void setRawDateNumber(DateTime *p, double r){
   p->s = r;
   p->rawS = 1;
+  p->tzSet = 1;
   if( r>=0.0 && r<5373484.5 ){
     p->iJD = (sqlite3_int64)(r*86400000.0 + 0.5);
     p->validJD = 1;
@@ -610,6 +612,7 @@ static int toLocaltime(
   p->validHMS = 1;
   p->validJD = 0;
   p->rawS = 0;
+  p->tzSet = 0;
   p->validTZ = 0;
   p->isError = 0;
   return SQLITE_OK;

These simple tweaks only affect thus far undefined behaviour.

With this change in place SQLite recognises the result of now as UTC, so SELECT datetime('now', 'utc') does not (erroneously) try to convert now from the local time zone to UTC. The same is true for SELECT datetime(0, 'unixepoch', 'utc').

The check that prevents this from happening was already in place: SELECT datetime('now', 'utc', 'utc') would not try to convert twice.

This change passes the make test test suite, except for a single test:

--- a/test/tkt-bd484a090c.test
+++ b/test/tkt-bd484a090c.test
@@ -30,8 +30,8 @@ do_test 2.1 {
   catchsql { SELECT datetime('now', 'localtime') }
 } {1 {local time unavailable}}
 do_test 2.2 {
-  catchsql { SELECT datetime('now', 'utc') }
-} {1 {local time unavailable}}
+  lindex [catchsql { SELECT datetime('now', 'utc') }] 0
+} {0}

This test is testing the unavailability of the utc modifier under SQLITE_TESTCTRL_LOCALTIME_FAULT. It fails because now datetime('now', 'utc') does not invoke osLocaltime anymore, since the time is known to already be UTC.

A test like datetime('2000-01-01 00:00', 'utc') could be used instead.

(2) By Stephan Beal (stephan) on 2024-03-04 18:05:19 in reply to 1.1 [link] [source]

I'd like to propose a few small tweaks of date handling functions. In particular, this patch:

See src:dc569683748354a6 :).

(3.1) By Nuno Cruces (ncruces) on 2024-03-05 02:14:31 edited from 3.0 in reply to 2 [link] [source]

Ah, teaches me to let sleeping dogs lie. :)

This wrecks some functions I appended to the amalgamation to format times with timezone offset.

Good change though!