Sling Academy
Home/SQLite/How to Work with Date Arithmetic Using SQLite Functions

How to Work with Date Arithmetic Using SQLite Functions

Last updated: December 08, 2024

Working with dates is a common necessity in database management, and SQLite offers a suite of functions that make date arithmetic straightforward and efficient. This article will guide you through understanding and using SQLite's date and time functions to perform calculations, comparisons, and modifications on date values.

Understanding SQLite Date and Time Functions

SQLite provides five date and time functions: date(), time(), datetime(), julianday(), and strftime(). These functions are used to extract or modify information from date and time values. They accept a variety of date and time formats, from literals to relative times expressed as keywords.

Common Date Formats

  • YYYY-MM-DD - 4-digit year, 2-digit month, 2-digit day (e.g., 2023-10-31)
  • HH:MM - 2-digit hour, 2-digit minute (e.g., 14:30)
  • HH:MM:SS - 2-digit hour, 2-digit minute, 2-digit second (e.g., 14:30:45)
  • YYYY-MM-DD HH:MM:SS - Combined date and time
  • now - Represents the current date and time

Adding and Subtracting Dates

The date arithmetic capabilities of SQLite can be very useful when you need to add or subtract time intervals.

Adding a Period to a Date

Let's start with adding a period, such as a number of days, to a date:


SELECT date('2023-10-31', '+10 days');

This query will return the date 10 days after October 31, 2023.

Subtracting a Period from a Date

In a similar way, you can subtract days from a date:


SELECT date('2023-10-31', '-10 days');

This will give you the date 10 days before October 31, 2023.

More Complex Operations

SQLite allows more complex date arithmetic, such as adding months or computing the difference in weeks:


SELECT date('2023-10-31', '+5 months');
SELECT date('2023-10-31', '+2 years', '-3 months');
SELECT julianday('2023-10-31') - julianday('2023-09-01');

In these examples:

  • The first query computes the date five months after October 31, 2023.
  • The second query addresses two modifications at once, showing how you can chain arithmetic modifiers.
  • The third query calculates the difference in days between two dates, using the julianday() function.

 

Formatting Dates with strftime()

The strftime() function is SQLite's answer to formatting date strings in useful patterns:


SELECT strftime('%Y-%m', 'now');
SELECT strftime('%d/%m/%Y', '2023-10-15');
SELECT strftime('%H:%M:%S', 'now');

This utility converts date strings into a desired format.

  • The first query returns the current year and month.
  • The second turns a date into a more familiar day/month/year format.
  • The third query zeroes in on the time for the current moment.

 

Example Usage in Applications

Assume you are developing a project management application. You might need to calculate deadlines based on a start date and a duration. SQLite’s functions make this task smoother:


CREATE TABLE projects (
  id INTEGER PRIMARY KEY,
  name TEXT,
  start_date TEXT,
  end_date TEXT AS (date(start_date, '+30 days'))
);

In this example, every project ends 30 days after its start date, using date arithmetic embedded in table creation.

Conclusion

Mastering the use of SQLite's date and time functions opens up a wide range of potential operations in your applications, from simple date additions to complex formatting needs. By understanding how these functions work, you can effectively manage date data in your database, keeping your applications timely and accurate.

Next Article: Practical Examples of Mathematical Calculations in SQLite

Previous Article: Advanced String Manipulation in SQLite with Built-in 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