8/23/18
Date Functions
SQLite supports five date and time functions
INFO151 Databases 1. date(timestring, modifier, modifier, ...)
Returns the date in default format: YYYY-MM-DD
2. time(timestring, modifier, modifier, ...)
Returns the time in default format: HH: MM:SS
Lecture 6 Handling Dates 3. datetime(timestring, modifier, modifier, ...)
YYYY-MM-DD HH:MM:SS
4. julianday(timestring, modifier, modifier, ...)
the julianday function counts the number of days since noon in Greenwich on November 24, 4713
B.C.E.
5. strftime(format, timestring, modifier, modifier, ...)
returns the date formatted according to the format string specified as the first argument
Date Functions Date Functions
• The time string can be followed by zero or more modifiers that alter show the current date date(timestring, modifier,
date and/or time. SELECT date('now') AS Today; modifier, ...)
• Each modifier is a transformation that is applied to the time value to its
left.
• Modifiers are applied from left to right; order is important
• e.g.,
SELECT datetime('now');
datetime(timestring, modifier, modifier, ...) datetime(timestring,
YYYY-MM-DD HH:MM:SS modifier, modifier, ...)
3 4
Modifiers date(timestring, modifier, modifier, ...)
Modifiers date(timestring, modifier, modifier, ...)
• NNN days Add (subtract) some amount of time to • start of month Shift the date backwards to the beginning of
• NNN hours • start of year the current month, year or day.
the date and time specified by the
• NNN minutes timestring and modifiers. • start of day
• NNN.NNNN seconds
• NNN months SELECT flno, departure,
• NNN years DATE(departure,'start of month')
FROM Flight;
Select datetime('now') as current_time,
datetime('now','1 days','1 hour','1 minute','1 second','1 year','1 month') as modified_time
SELECT flno, departure, DATE(departure,'start of
month‘, ‘3 days’)
FROM Flight;
5 6
1
8/23/18
weekday N Example: Date Calculations
• Advances the date forward to the next date where the weekday • Compute the duration of each flight in hours
number is N. Sunday is 0, Monday is 1, and so forth. SELECT flno, departure, arrival,
(julianday (arrival) - julianday (departure))*24 AS duration
SELECT date('now', 'weekday 0') FROM Flight;
7 8
strftime(format, timestring, modifier, modifier, ...)
SELECT flno, DateTime(departure),
Date(departure), Time(departure), strftime('%Y', departure) AS Year,
strftime('%m', departure) AS Month,
Format Description
strftime('%d', departure) AS Day
FROM Flight %d day of month: 00
%f fractional seconds: SS.SSS
%H hour: 00-24
%j day of year: 001-366
%J Julian day number
%m month: 01-12
%M minute: 00-59
%s seconds since 1970-01-01
%S seconds: 00-59
%w day of week 0-6 with Sunday==0
%W week of year: 00-53
%Y year: 0000-9999 9