Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
346 views
in Technique[技术] by (71.8m points)

android - Sorting dates in sqlite database?

I have developed an App ..For that I have a database and it has many tables. One of the table has date column. My question is I have to sort the dates and have to pick oldest one Like Oct-24-2012 from below table column

Column_Date
------------

Nov-07-2012
Nov-21-2012
Nov-25-2012
Oct-25-2012
Oct-24-2102

How should I do that....I have stored the date column in string... If I need to change the datatype for date Column, Let me know which Datatype should i used. And How Should I sort the Column.According to That datatype..

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

In sqlite does not really have a date type. You can store dates as strings using one of their predefined formats see http://www.sqlite.org/lang_datefunc.html for more information.

A time string can be in any of the following formats:

YYYY-MM-DD
YYYY-MM-DD HH:MM
YYYY-MM-DD HH:MM:SS
YYYY-MM-DD HH:MM:SS.SSS
YYYY-MM-DDTHH:MM
YYYY-MM-DDTHH:MM:SS
YYYY-MM-DDTHH:MM:SS.SSS
HH:MM
HH:MM:SS
HH:MM:SS.SSS
now
DDDDDDDDDD

You need to store them in YYYY-MM-DD then you can sort them order by asc limit 1 to get the oldest date. So instead of

Column_Date
------------
Nov-07-2012
Nov-21-2012
Nov-25-2012
Oct-25-2012
Oct-24-2102

You will have to store them like this instead

Column_Date
------------
2012-11-07
2012-11-21
2012-11-25
2012-10-25
2012-10-24

Finally you read the rows if any

Cursor oldestDateCursor = db.query("DateTableName", null, null, null, null, null, "date_column ASC LIMIT 1");
if (oldestDateCursor.moveToFirst())
{
    String date = oldestDateCursor.getColumnName(oldestDateCursor.getColumnIndex("date_column"));
}
oldestDateCursor.close();

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...