2

Possible Duplicate:
Sort the date in Sqlite database

I am creating an iPhone application that used SQLite database. In this I have a table that contains three columns and one column is "ReleaseDate" with DATE datatype. I want to sort the database with respect to the dates in this column. I used the following code. For inserting,

    NSDateFormatter *format = [[NSDateFormatter alloc]init];
    [format setDateFormat:@"MM/dd/yyyy"];
    NSDate *dateFromString = [[NSDate alloc] init];
    dateFromString = [format dateFromString:date];
    [format release];
    NSTimeInterval timeInterval = [dateFromString timeIntervalSince1970];

    sqlite3_bind_double(insertStmt, 4, timeInterval); 

here, 'date' is a string value that holds the date value. Now, how can I retrieve data from entire columns from the DB? the query I used is,

select * from ItemTable  order by ReleaseDate desc

but sorting is not done.

Community
  • 1
  • 1
Mithun
  • 459
  • 1
  • 10
  • 32
  • FYI: if you were using Foundation types all the way down the stack, you could look into NSSortDescriptor. In general, it's a good way to sort arrays of structured information. – Eric G May 25 '12 at 06:18

3 Answers3

2

There should be a format for dates in SQLite called DateTime. Try formatting your date to that as opposed to a String.

http://metacpan.org/pod/DateTime::Format::SQLite

szabgab
  • 6,202
  • 11
  • 50
  • 64
pandavenger
  • 1,017
  • 7
  • 20
0

Use like this: select * from ItemTable ORDER BY ReleaseDate ASC/DESC

Deepzz
  • 4,573
  • 1
  • 28
  • 52
-1

When you are inserting data use following code.

NSString *strTimeStamp = [NSString stringWithFormat:@"%lf",[[NSDate date] timeIntervalSince1970]];

Insert strTimeStamp to Database.

When you are getting data please use following function

NSTimeInterval timeInterval= [self intervalBeforeDays:2];

NSString *query = [NSString stringWithFormat:@"Select * from pictures where date >= %lf",timeInterval];



- (NSTimeInterval)intervalBeforeDays:(NSInteger)day{
    NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
    NSDateComponents *dateComponents = [gregorian components:(NSDayCalendarUnit | NSMonthCalendarUnit | NSYearCalendarUnit) fromDate:[NSDate date]];
    NSInteger iday = [dateComponents day];
    NSInteger iEarlierDay = iday -day;
    dateComponents.day = iEarlierDay;
    NSDate *date = [gregorian dateFromComponents:dateComponents];
    NSTimeInterval interval = [date timeIntervalSince1970];
    [gregorian release];
    return interval;

}
BoltClock
  • 700,868
  • 160
  • 1,392
  • 1,356
iPhone developer.
  • 2,122
  • 1
  • 16
  • 17