Search code examples
ios7.1tapku

Convert a NSString to a NSDate


I have a NSString like this 05/09/2015 then I want to convert it into this format 2014-07-28 18:30:00 +0000

that second date was the one that I get from the system date. That date can be placed nicely on Tapku calender. but my string is the first one. I want to convert that 1st date just like as the date format that im getting from the system date. How can I do that.

Please help me. Thanks


Solution

  • NSString to NSDate

    NSString *dateString = @"01-02-2010";
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    // this is imporant - we set our input date format to match our input string
    // if format doesn't match you'll get nil from your string, so be careful
    [dateFormatter setDateFormat:@"dd-MM-yyyy"];
    NSDate *dateFromString = [[NSDate alloc] init];
    // voila!
    dateFromString = [dateFormatter dateFromString:dateString];
    
    NSDateFormatter *otherFormatter = [[NSDateFormatter alloc] init];
    [otherFormatter setDateFormat:@"yyyy-MM-dd"];
    //[otherFormatter setTimeStyle:NSDateFormatterMediumStyle];
    
    NSString *resultString = [otherFormatter stringFromDate:dateFromString];
    NSLog(@"%@", resultString);
    

    And then you can convert it back to an NSDate or keep as an NSString.

    See this: Click Here