Table of Contents

SQLite - Date

About

The date data type in SQLite context does not exist. It is not an affinity.

SQLite are capable of storing dates and times with the following data type (affinity) as:

You use then the sqlite date function to manipulate them.

SQLite transforms any date value to UTC+0000.

For instance, you can store a date as a string of:

Management

Init

See the Date Functions

select date(time-value, "modifier", "modifier", ...)
select time(time-value, "modifier", "modifier", ...)
select datetime(time-value, "modifier", "modifier", ...)
...

where the date function:

where the time-value may be:

Example: the following string are the same date

select date("2018-01-01")
select date("2458119.5") -- Julian number

You got the julian number with select julianday(date(“2018-01-01”))

Add / Substract

See the modifiers of the Date Functions

Example:

select date("2018-01-01",'-1 days')
2017-12-31

select date("2018-01-01",'+1 months')
2018-02-01

select date("2018-01-01",'2 years')
2020-01-01

Diff

 SELECT julianday(first) - julianday(second) 
SELECT (strftime('%s','2018-01-22T00:01:29') - strftime('%s','2018-01-20T00:01:29'))/60/60/24;
2 

Get weekday names in English

Sqlite does not handle the week day name. You need to get the day of the week with the %w strftime format modifier and wrap it in a case statement

Example

select case cast(strftime('%w', date()) as integer)
           when 0 then 'Sunday'
           when 1 then 'Monday'
           when 2 then 'Tuesday'
           when 3 then 'Wednesday'
           when 4 then 'Thursday'
           when 5 then 'Friday'
           else 'Saturday' end as english_weekday

Date function

See the modifiers of the date Functions

Example:

select date("2018-01-02",'start of month')
2018-01-01

select date("2018-01-02",'weekday 2')
2018-01-02 -- A tuesday

Format / Output

strftime

select strftime("%m-%d-%Y","2018-01-01")
01-01-2018

from Epoch (Jdbc)

If your date is stored in epoch format, you can use the datetime function

As javase/9/docs/api/java/sql/Date.html stores the epoch date with milliseconds in epoch format, you need to divide by 1000

Example

select datetime(myDateColumn/1000,'unixepoch') from myTable
select datetime(myDateColumn/1000,'unixepoch','localtime') from myTable

Query Example

select 
  * 
from 
  redirections_log 
where 
  datetime(timestamp) > datetime('now','-5 minutes')
order by 
  datetime(timestamp) desc;
select 
  strftime('%H:%M', timestamp), 
  count(1) 
from 
  redirections_log 
group by 
  strftime('%H:%M', timestamp)

Documentation / Reference