objective-csqlitensdatedate-format

How to convert a DD-MM-YYYY date format string into a YYYY-MM-DD date format string or into a NSDate object in Objective-C?


I have read date from XML which give me back string where the date is like DD-MM-YYYY. But when I want to add it to my core data database, SQLite sorts me that wrong so I have to convert it to date format or to string like: YYYY-MM-DD. But SQLite does not support either Date() or To_Date() functions. Can you help me?


Solution

  • You can use NSDateFormatter to format a date in Objective C.

    Here's a quick example which might not do exactly what you want, but should hopefully give some pointers:

    // Convert my dd-mm-yyyyy string into a date object
    NSString *stringDate = @"01-02-2011";
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"dd-MM-yyyy"];
    
    NSDate *date = [dateFormatter dateFromString:stringDate];
    
    // Convert my date object into yyyy-mm-dd string object
    [dateFormatter setDateFormat:@"yyyy-MM-dd"];
    NSString *formattedStringDate = [dateFormatter stringFromDate:date];
    
    [dateFormatter release];