SQLite has a date()
function that enables you to return a date value based on a time string and any modifiers.
It returns the date in this format: YYYY-MM-DD
To use this function, you need to provide a time string, plus any (optional) modifiers. A modifier allows you to change the date, such as add a number of days, set it to local time, etc
Syntax
The syntax of the date()
function goes like this:
date(timestring, modifier, modifier, ...)
The timestring
argument must be a valid time string.
The modifier
arguments are optional. You can provide one or more modifiers. If you provide a modifier, it must be a valid modifier.
Example
Here’s an example to demonstrate the date()
function being used with one argument.
SELECT date('now');
Result:
2020-04-27
The now
time string is converted into the current date and time. Given I’m using the date()
function, only the date is returned.
Add a Modifier
We can modify the previous result by using a modifier. Here’s an example.
SELECT date('now', '+6 months');
Result:
2020-10-27
In this case, I added six months to the date.
Multiple Modifiers
As mentioned, you can add one or more modifiers. Here’s an example of adding another modifier to the previous example.
SELECT date('now', '+6 months', 'localtime');
Result:
2020-10-28
In my case, the localtime
modifier resulted in a day being added to the date.
The reason it does this is because the localtime
modifier assumes the time string provided is in Universal Coordinated Time (UTC). It then adjusts the time string so that it displays local time.
Therefore, you may get a different result, depending on your local time.
String Literal as the Time String
The above examples use now
as the time string, but you can provide any valid time string.
Here’s a few other examples.
SELECT date('2020-04-27 23:58:57');
Result:
2020-04-27
In this case it simply removes the time portion from the date.
Here it is again, but with some modifiers.
SELECT date('2020-04-27 23:58:57', 'start of year', '+6 months');
Result:
2020-07-01
In this case I wanted to get the date that is 6 months from the start of the year of the date provided.
Here’s an example that uses the Julian Day as the time string.
SELECT date('2458967.49737293');
Result:
2020-04-27
date() vs strftime()
The date()
function returns exactly the same result that strftime('%Y-%m-%d', ...)
returns. The date()
function is just a more convenient way to do it.
SELECT
date('now'),
strftime('%Y-%m-%d', 'now');
Result:
date('now') strftime('%Y-%m-%d', 'now') ----------- --------------------------- 2020-04-28 2020-04-28
Date Range
As with all SQLite date and time functions, date()
only works for dates between 0000-01-01 00:00:00 and 9999-12-31 23:59:59 (julian day numbers 1721059.5 through 5373484.5).
For dates outside that range, the results are undefined.