我想補充有關使用SQLite日期和時間與UNIX紀元時間的一些信息:
Unix紀元爲1970-01-01 00:00:00,即1日午夜一月1970. UNIX計算機上的當前時間(如運行Linux的計算機)以秒爲單位進行測量。
SQLite支持這個紀元時間,並且我發現它非常適合用作SQLite中DateTime字段的格式。
具體而言,假設我想要一個事件表,用於諸如音樂會等事件。我希望fromDateTime字段在事件啓動時存儲。我能做到這一點通過設置fromDateTime提起Integer類型,因爲這樣的:
CREATE TABLE IF NOT EXISTS Event(
eventID INTEGER PRIMARY KEY,
name TEXT,
ratingOutOf10 REAL,
numberOfRatings INTEGER,
category TEXT,
venue TEXT,
fromDateTime INTEGER,
description TEXT,
pricesList TEXT,
termsAndConditions TEXT
);
現在,讓我們以UNIX新紀元使用SQLite日期時間字段的用法:
Basic
select strftime('%s', '2016-01-01 00:10:11'); --returns 1451607012
select datetime(1451607012, 'unixepoch'); --returns 2016-01-01 00:10:11
select datetime(1451607012, 'unixepoch', 'localtime'); --returns 2016-01-01 05:40:11 i.e. local time (in India, this is +5:30).
Only dates and/or times:
select strftime('%s', '2016-01-01'); --returns 1451606400
select strftime('%s', '2016-01-01 16:00'); --returns 1451664000
select date(-11168899200, 'unixepoch'); --returns 1616-01-27
select time(-11168899200, 'unixepoch'); --returns 08:00:00
Other stuff:
select strftime('%d-%m-%Y %H:%M:%S', '2012-09-13 12:44:22') --returns 13-09-2012 12:44:22
現在,這裏是一個上面的例子使用我們的事件表:
EXAMPLE:
insert into Event
(name, ratingOutOf10, numberOfRatings, category, venue, fromDateTime, description, pricesList, termsAndConditions)
VALUES
('Disco', '3.4', '45', 'Adventure; Music;', 'Bombay Hall', strftime('%s','2016-01-27 20:30:50'), 'A dance party', 'Normal: Rs. 50', 'Items lost will not be the concern of the venue host.');
insert into Event
(name, ratingOutOf10, numberOfRatings, category, venue, fromDateTime, description, pricesList, termsAndConditions)
VALUES
('Trekking', '4.1', '100', 'Outdoors;', 'Sanjay Gandhi National Park', strftime('%s','2016-01-27 08:30'), 'A trek through the wilderness', 'Normal: Rs. 0', 'You must be 18 or more and sign a release.');
select * from event where fromDateTime > strftime('%s','2016-01-27 20:30:49');
我喜歡這個解決方案,因爲它真的很容易與編程語言工作,不參與各種形式的太多的思考SQLite的DATE,TIME,DATETIME等數據類型。
有關'strftime'的詳細信息,請參閱https://www.sqlite.org/lang_datefunc.html上的文檔。 – 2012-09-13 12:35:17
我檢查了文檔,並嘗試了很多東西......我只是困惑如何把這個確切的查詢,因爲在我的數據庫中我有不同日期格式和sqlite strftime函數提取不同的一個。 – vishalg
@vishalg也許你想用更詳細的信息來更新這個問題,用數據庫的示例值更好。 –