Sling Academy
Home/SQLite/Mastering Date and Time Functions in SQLite: DATE and DATETIME

Mastering Date and Time Functions in SQLite: DATE and DATETIME

Last updated: December 08, 2024

SQLite is a software library that provides a relational database management system. It is widely used because of its lightweight, serverless, and self-contained nature. For many applications, managing date and time effectively is crucial. SQLite offers robust functions to handle date and time, primarily through the DATE and DATETIME functions.

Understanding Date and Time Functions in SQLite

SQLite date and time functions allow you to work with date and time values effectively. These functions can be used to manipulate and format date/time values, which is essential for data analytics and reporting. The primary functions you'll frequently encounter or use include DATE, TIME, DATETIME, JULIANDAY, and STRFTIME.

The DATE Function

The DATE function in SQLite enables you to extract the date part from a date-time value. This function can be used when you are interested in treating only the date component of a date-time entry. You can use the following syntax for the DATE function:

DATE(timestring, modifier1, modifier2, ...)

Here, timestring is a string that conforms to a date or date-time format, and modifiers are used to alter the timestring. Consider the following example:

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

The DATETIME Function

The DATETIME function in SQLite provides full control over both date and time components. The function's syntax is:

DATETIME(timestring, modifier1, modifier2, ...)

It allows for conversion between time formats and computation of intervals. Here's a simple usage example:

SELECT DATETIME('2023-10-10 12:34:50');  -- Returns the given datetime

Working with Modifiers

SQLite provides flexibility through modifiers. Modifiers can be used to manipulate the time component. Here are some common modifiers:

  • +N days: Add N days to the timestring.
  • -N hours: Subtract N hours from the timestring.
  • start of month: Fast forward to the start of the current month.

Using these modifiers can greatly simplify complex date-time computations. For example:

SELECT DATE('now', 'start of month', '+1 month', '-1 day');  -- Returns the last day of the current month

Additional Date-Time Functions

Beyond date and date-time functions, SQLite offers additional functions such as:

  • TIME: Returns the time as HH:MM:SS format.
  • JULIANDAY: Converts a date into a Julian day number.
  • STRFTIME: Formats the date-time formatted string according to a specified format.

For example, using STRFTIME:

SELECT STRFTIME('%Y-%m-%d %H:%M:%S', 'now');  -- Returns the current date and time

Practical Use Case

Let's consider a practical example where we need to calculate an individual's age based on the birthdate stored in the database. We'll retrieve the current date and subtract the birth date:

SELECT strftime('%Y', 'now') * 1 - strftime('%Y', birthdate) * 1 
    - (strftime('%m-%d', 'now') < strftime('%m-%d', birthdate)) AS age 
FROM persons;

In this example, strftime is used to extract the year from the current date and the birthdate, calculating the age accordingly.

Conclusion

The DATE and DATETIME functions provide powerful tools for manipulating and querying date and time data within SQLite. By understanding how to leverage these functions along with their modifiers, you can handle complex temporal calculations and format controls within your applications, making your data processing more effective and reliable.

Next Article: SQLite Mathematical Functions: A Comprehensive Guide

Previous Article: How to Use String Functions in SQLite: SUBSTR and REPLACE

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