SQLite Dates
No Date Type
SQLite has no special data type for dates. Dates are usually stored as text in the format YYYY-MM-DD, or YYYY-MM-DD HH:MM:SS with a time.
In this format, dates are sorted and compared in the right order. The Northwind database stores dates this way:
Below is a selection from the "Orders" table in the Northwind sample database:
| OrderID | CustomerID | EmployeeID | OrderDate | ShipperID |
|---|---|---|---|---|
| 10248 | 90 | 5 | 1996-07-04 | 3 |
| 10249 | 81 | 6 | 1996-07-05 | 1 |
| 10250 | 34 | 4 | 1996-07-08 | 2 |
Date and Time Functions
| Function | Returns |
|---|---|
| date() | The date, as YYYY-MM-DD |
| time() | The time, as HH:MM:SS |
| datetime() | The date and time, as YYYY-MM-DD HH:MM:SS |
| julianday() | The number of days since a day far back in history, as a decimal number |
| unixepoch() | The number of seconds since 1970-01-01 |
| strftime() | The date, formatted as you want |
The Current Date and Time
The value 'now' means the current date and time, in UTC:
Add the modifier 'localtime' to get the local time of your computer: datetime('now', 'localtime').
Calculate With Dates
Modifiers add or subtract time, or move to the start of a period:
Example
SELECT date('1996-07-04', '+7 days'),
date('1996-07-04', '+1 month'),
date('1996-07-04', 'start of month');
Try it Yourself »
Get a Part of a Date
strftime() formats a date. This example gets the year and the month of each order:
Example
SELECT OrderID, OrderDate,
strftime('%Y', OrderDate) AS Year,
strftime('%m', OrderDate) AS Month
FROM Orders;
Try it Yourself »
Orders per Month
Example
Count the orders in each month:
SELECT strftime('%Y-%m', OrderDate) AS Month,
COUNT(*) AS Orders
FROM Orders
GROUP BY Month;
Try it Yourself »
The Number of Days Between Two Dates
Subtract two julianday() values to get the number of days between two dates:
Format Codes
These are the most used codes for strftime():
| Code | Means | Example |
|---|---|---|
%Y | Year | 1996 |
%m | Month, 01 to 12 | 07 |
%d | Day of the month, 01 to 31 | 04 |
%H | Hour, 00 to 23 | 14 |
%M | Minute, 00 to 59 | 30 |
%S | Second, 00 to 59 | 05 |
%w | Day of the week, 0 to 6, where 0 is Sunday | 4 |
%j | Day of the year, 001 to 366 | 186 |