sqlite Date Sorting

2019-02-28 06:26发布

I am a parsing a file into a sqlite database that contains dates in the YYYY-MM-DD format. I want to store the entries into sqlite in such a way that I can sort the entries by date (strings not cutting it). What is the normal protocol for storing and ordering dates in sqlite? Should convert the dates into a number. Is there a way to convert YYYY-MM-DD dates into timestamps?

4条回答
女痞
2楼-- · 2019-02-28 06:33

If You want to Current TimeStamp then use

SELECT strftime('%s','now'); 

If You want toYYYY-MM-DD date TimeStamp then use

SELECT strftime('%s','YYYY-MM-DD'); 

where %s=seconds since 1970-01-01

查看更多
霸刀☆藐视天下
3楼-- · 2019-02-28 06:34

SQLite supports "DATE" in table creation. (More about that later.)

CREATE TABLE test (dt DATE PRIMARY KEY);
INSERT INTO "test" VALUES('2012-01-01');
INSERT INTO "test" VALUES('2012-01-02');
INSERT INTO "test" VALUES('2012-01-03');

SELECT dt FROM test ORDER BY dt;
2012-01-01
2012-01-02
2012-01-03

Values in the form yyyy-mm-dd sort correctly as either a string or a date. That's one reason yyyy-mm-dd is an international standard.

But SQLite doesn't use data types in the way most database workers expect it. Data storage is based on storage classes instead. For example, SQLite allows this.

INSERT INTO test VALUES ('Oh, bugger.');
SELECT * FROM test ORDER BY dt;
2012-01-01
2012-01-02
2012-01-03
Oh, bugger.

It also allows different date "formats" (actually, values) in a single column. Its behavior is quite unlike standard SQL engines.

INSERT INTO test VALUES ('01/02/2012');
SELECT * FROM test ORDER BY dt;
01/02/2012
2012-01-01
2012-01-02
2012-01-03
Oh, bugger.

You don't have to do anything special to store a timestamp in a date column. (Although I'd rather see you declare the column as timestamp, myself.)

INSERT INTO test VALUES ('2012-01-01 11:00:00');
SELECT * FROM test ORDER BY dt;
2012-01-01
2012-01-01 11:00:00
2012-01-02
2012-01-03
Oh, bugger.

SQLite will try to do the Right Thing as long as you feed consistent data into it. And it will sort dates correctly if you use the standard format.

查看更多
Juvenile、少年°
4楼-- · 2019-02-28 06:39

i have the date field store in this way DD/MM/YYYY. For sorting the date ( date field is a string ) i have to convert it before order it.

select   (substr(date, 7, 4) || '-' || substr(date, 4, 2) || '-' || substr(date, 1, 2)) as new_date from work_hour order by new_date desc
查看更多
我只想做你的唯一
5楼-- · 2019-02-28 06:49

Instead of storing date in format "YYYY-MM-DD", store the time-stamp of that date and that will help you to sorting the table.

查看更多
登录 后发表回答