The Complete Guide to SQLite's Date & Time Functions: Fixes and Formats

2025-10-23

The key thing to remember is that SQLite does not have a dedicated DATE or DATETIME storage class. Instead, it recommends storing date and time values as TEXT (ISO8601 strings), REAL (Julian day numbers), or INTEGER (Unix timestamps).

The biggest headache is using formats that SQLite's built-in date/time functions don't recognize.

If you try to insert or use a date string that isn't in a recognized ISO-8601 format (like YYYY-MM-DD HH:MM:SS or YYYY-MM-DD), the functions might return NULL or give incorrect results, especially when comparing.

Example of what NOT to do

-- SQLite's date functions might struggle with this format:
SELECT date('10/25/2025'); -- Likely returns NULL

Always stick to the ISO-8601 format (YYYY-MM-DD HH:MM:SS.SSS) for storing dates as TEXT. If you need a different format for display, use the incredibly flexible strftime() function.

Sample Code

-- Use ISO-8601 when inserting or using 'now'
INSERT INTO my_table (event_time) VALUES ('2025-10-25 10:30:00'); 

-- Alternative: Use date() or datetime() for current time, which returns ISO-8601
INSERT INTO my_table (event_time) VALUES (datetime('now')); 

-- Use strftime() to display a date in a custom format (e.g., DD-MM-YYYY)
SELECT strftime('%d-%m-%Y', event_time) AS formatted_date
FROM my_table;

By default, SQLite's date/time functions operate in UTC (Coordinated Universal Time). Forgetting this can lead to records showing up at the wrong time.

Using datetime('now') will give you the current UTC time. If your application or users expect local time, you'll see a time difference.

To get your system's local time, simply add the 'localtime' modifier to the function call.

Sample Code

-- Get the current UTC date and time (The default)
SELECT datetime('now'); 
-- Output: 2025-10-25 11:44:00 

-- Get the current local date and time
SELECT datetime('now', 'localtime');
-- Output: 2025-10-25 20:44:00 (If local time is UTC+9)

You might be tempted to do date arithmetic by extracting parts and comparing them, which is complicated and error-prone.

Trying to find records from the last 7 days by comparing substrings or other complicated logic.

The easiest way to compare and calculate dates is using the built-in modifiers or converting dates to Julian Day Numbers (a REAL number representing the days since noon on Nov 24, 4714 BC).

Sample Code (Using Modifiers for Calculation)

-- Find all records from the last 7 days
SELECT *
FROM my_table
WHERE event_time >= datetime('now', '-7 days');

-- Calculate the date 3 months and 1 day in the future
SELECT date('now', '+3 months', '+1 day', 'localtime');

Sample Code (Using julianday() for Difference)

-- Find the number of days between two dates
SELECT julianday('2025-12-31') - julianday('2025-10-25') AS days_remaining;
-- Output: 67.0

A highly recommended and performant way to store and manage timestamps in SQLite is using the Unix Epoch—the number of seconds since 1970-01-01 00
00
00 UTC. This is stored as a simple INTEGER.

Fast Comparisons
Comparing integers is much faster than comparing strings.

Universal
It's timezone-neutral (UTC-based).

Simple Math
Date arithmetic is just simple addition/subtraction of seconds.

-- 1. Create a table using INTEGER for the timestamp
CREATE TABLE log_entries (
    id INTEGER PRIMARY KEY,
    message TEXT,
    timestamp INTEGER -- Storing the Unix Epoch
);

-- 2. Insert the current Unix timestamp
-- Use strftime('%s', ...) to get the current epoch seconds
INSERT INTO log_entries (message, timestamp)
VALUES ('User login success', strftime('%s', 'now')); 

-- 3. Query records from the last 1 hour (3600 seconds)
SELECT *
FROM log_entries
WHERE timestamp >= strftime('%s', 'now', '-1 hour');

-- 4. Convert the Unix timestamp back to a readable date/time string (local time)
SELECT message, datetime(timestamp, 'unixepoch', 'localtime') AS local_time_string
FROM log_entries;

sqlite



Boosting SQLite Writes with PRAGMAs and CHUNK_SIZE

Here's a friendly breakdown of this feature, common pitfalls, and an alternative approach.SQLITE_FCNTL_SIZE_HINT is an opcode used with the sqlite3_file_control() C function


SQLite Performance Tuning with SQLITE_STMTSTATUS_SORT

The most common "trouble" isn't a bug but rather an unexpectedly high value for SQLITE_STMTSTATUS_SORT, which signals that your query is inefficient


SQLite C Interface: How to Pause Execution

If you're looking to pause or delay a C program that uses SQLite, you need to use a function from the standard C library or a platform-specific library



Beyond Blocking: Effective SQLite Concurrency Control in C

SQLITE_FCNTL_BLOCK_ON_CONNECT is a flag you can set using sqlite3_file_control() to ensure that when a new process tries to open a database file


Exploring SQLITE_FCNTL_ROLLBACK_ATOMIC_WRITE: A Deep Dive

Let's dive into the fascinating world of SQLite's SQLITE_FCNTL_ROLLBACK_ATOMIC_WRITE file control. It's a bit of a niche topic


Beyond SELECT: Using PRAGMA table_info for Direct SQLite Schema Inspection in C

The function you're likely referring to is sqlite3_column_database_name (and its siblings like sqlite3_column_table_name


SQLite's Base85() Function: Common Issues and Alternatives

The Base85() function is a non-standard SQL function that can be enabled in SQLite. It's used to encode binary data into a text format


Beyond Basics: Managing State and Callbacks in SQLite's Streaming Session Interface

Let's dive in!The "streaming" versions of the SQLite Session Module API are designed for efficiently handling a large number of changes


Mastering SQLite's C Interface Globbing

The primary function you use for this is sqlite3_stricmp16 with a globbing pattern. One of the most common issues people run into is a misunderstanding of how the function works or an unexpected return value


Mastering SQLite Checkpointing: Common Issues and Solutions

Checkpointing is the process of moving committed transactions from the WAL file back into the main database file. In WAL mode