Date format needed to work 'order by date' query in iOS

I am storing list of data in sqlite for my iOS app . In DB one column 'addedOn' stores dates from server response in format '30-Jul-2014 07:43:20'. Here I have tried many things on 'addedOn' column but could not fetch date in ASC/DESC order. Some other details are

  • Column 'addedOn' date type is DATETIME.
  • Queries tried to fetch in DESC used are:
  • "SELECT * FROM tableName ORDER BY datetime(addedOn) DESC LIMIT 1" & "SELECT * FROM tableName ORDER BY date(addedOn) DESC LIMIT 1" & "SELECT * FROM tableName ORDER BY addedOn DESC LIMIT 1".

    But all these queries failed to give me expected result.

  • I tried to convert this date in another format while inserting in DB it self but converting of this date format in other date format like 'yyyy-MM-dd HH:mm:ss' isn't working at all. For that tried below code:

    NSString *dateString = @"30-Jul-2014 07:43:20"; NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"]; NSDate *dateFromString = [[NSDate alloc] init]; dateFromString = [dateFormatter dateFromString:dateString];

    NSString *stringDate = [dateFormatter stringFromDate:dateFromString];
    NSLog(@"stringDate %@", stringDate);
    
  • So my question is this possible to convert this type format in any other format or is there any thing else that I am missing. Please share your thought and suggest me the changes that I need to do. Any help is appreciated.


    I have my DB with SQLite & have date in format "dd-mmm-yyyy HH:mm:ss" in which the below query works..

    SELECT * FROM TableName ORDER BY addedOn ASC

    ASC|DESC can be used as per requirement..

    And if you want to convert your date format than do as under :

    NSString * dateStr = @"30-Jul-2014 07:43:20";
    NSDateFormatter *dateFormat = [[NSDateFormatter alloc]init];
    [dateFormat setDateFormat:@"dd-MMM-yyyy HH:mm:ss"];
    
    NSDate *date = [dateFormat dateFromString:dateStr];
    [dateFormat setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSString *finalString = [dateFormat stringFromDate:date];
    

    here the output is finalString = "2014-07-30 07:43:20"


    Your dataFormat seems to be wrong. Try the following DateFormat.

    [dateFormatter setDateFormat:@"dd-MMM-yyyy HH:mm:ss"];
    
    NSDate *date = [dateFormatter dateFromString:yourDateString];
    

    This will give you exact date.

    Hope it helps..


    NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"creationDate" ascending:YES];
    

    尝试使用NSPredict并使用上面的代码

    链接地址: http://www.djcxy.com/p/35172.html

    上一篇: 我可以使用NSDateFormatter将此日期字符串转换为NSDate吗?

    下一篇: 在iOS中按'按日期排序'查询所需的日期格式