Sling Academy
Home/SQLite/Date and Time Manipulations in SQLite Applications

Date and Time Manipulations in SQLite Applications

Last updated: December 08, 2024

SQLite is a powerful, lightweight, file-based database engine that is often used in mobile apps, embedded devices, and other applications where efficient storage and retrieval of data are required. One common task in managing databases is handling date and time values. SQLite offers a variety of functions to manipulate and format these values, making it easier to store, query, and display date and time data in an efficient manner.

Understanding SQLite Date and Time Storage

SQLite does not have dedicated date and time storage types such as DATE or TIME. Instead, dates and times can be stored as TEXT, INTEGER, or REAL values, depending on the format:

  • TEXT: Dates are stored as strings in the format "YYYY-MM-DD HH:MM:SS" (ISO 8601).
  • INTEGER: Time as Unix Time, the number of seconds since 1970-01-01 00:00:00 UTC.
  • REAL: Julian day numbers represent the number of days since noon in Greenwich on November 24, 4714 B.C.

Basic Date and Time Functions

SQLite provides built-in functions for date and time manipulations which include date(), time(), datetime(), julianday(), strftime(), and more. Here’s how you can use some of these functions:

Using the date() Function

The date() function returns the date in 'YYYY-MM-DD' format. Here’s a simple example:

SELECT date('now'); -- Returns the current date

You can also add or subtract intervals from the current date:

SELECT date('now', '+1 day'); -- Returns tomorrow's date

 

Using the datetime() Function

The datetime() function returns the timestamp in 'YYYY-MM-DD HH:MM:SS' format:

SELECT datetime('now'); -- Returns current date and time

You can combine it with modifiers similar to date():

SELECT datetime('now', '-1 hour'); -- Returns the date and time an hour ago

Using the strftime() Function

The strftime() function is useful for custom formatting:

SELECT strftime('%Y-%m-%d %H:%M:%S', 'now'); -- Flexible format control

You can extract specific components like the year or month from a date:

SELECT strftime('%Y', 'now'); -- Extracts the current year

Combining Date and Time Operations with SQL Queries

Efficient querying often requires using these functions to filter and manipulate data. Consider the following example where we want to retrieve all entries added in the last 30 days:


SELECT * FROM tasks
WHERE date(added_date) >= date('now', '-30 days');

This query assumes there's a table named tasks with a column added_date storing date information.

Calculating Time Differences

To find the difference between two datetime values, you can use Julian day calculations or simple subtraction if stored as Unix timestamps:


-- Using unix timestamps
SELECT (strftime('%s','now') - strftime('%s', '2023-09-01 12:00:00')) / 60 / 60 / 24;

This example calculates the number of days between now and a past date, converting seconds to days.

Conclusion

Manipulating date and time in SQLite is both powerful and flexible. By understanding and using its built-in functions, you can handle almost any date and time-related calculation, formatting or extraction easily within your SQLite databases. As you continue to grow your applications, mastering these techniques will be integral to efficient data management and user interface design.

Next Article: Using Mathematical Functions to Enhance SQLite Performance

Previous Article: Optimizing Queries with SQLite String Functions

Series: SQLite Functions and Extensions

SQLite

You May Also Like

  • How to use regular expressions (regex) in SQLite
  • SQLite UPSERT tutorial (insert if not exist, update if exist)
  • What is the max size allowed for an SQLite database?
  • SQLite Error: Invalid Value for PRAGMA Configuration
  • SQLite Error: Failed to Load Extension Module
  • SQLite Error: Data Type Mismatch in INSERT Statement
  • SQLite Warning: Query Execution Took Longer Than Expected
  • SQLite Error: Cannot Execute VACUUM on Corrupted Database
  • SQLite Error: Missing Required Index for Query Execution
  • SQLite Error: FTS5 Extension Malfunction Detected
  • SQLite Error: R-Tree Node Size Exceeds Limit
  • SQLite Error: Session Extension: Invalid Changeset Detected
  • SQLite Error: Invalid Use of EXPLAIN Statement
  • SQLite Warning: Database Connection Not Closed Properly
  • SQLite Error: Cannot Attach a Database in Encrypted Mode
  • SQLite Error: Insufficient Privileges for Operation
  • SQLite Error: Cannot Bind Value to Parameter
  • SQLite Error: Maximum String or Blob Size Exceeded
  • SQLite Error: Circular Reference in Foreign Key Constraints