Search code examples
iosobjective-cnsdate

Weird converting output from NSString to NSDate


I have weird result trying to output NSDate object from NSString. My NSString is: 1976-06-11 My method to convert is:

-(NSDate*)dateFromString:(NSString *)dateString{

    // Convert string to date object
    NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
    [dateFormat setDateFormat:@"yyyy-MM-dd"];
    NSDate *date = [dateFormat dateFromString:dateString];
    return date;
}

But it output 1976-06-10 21:00:00 +0000

How could that happen? Difference in 1 day.


Solution

  • You can use following methods to convert an UTC date string into UTC date and local date

     - (NSDate *)convertIntoGMTZoneDate:(NSString *)dateString
        {
            NSDateFormatter *gmtFormatter = [[NSDateFormatter alloc]init];
            [gmtFormatter setDateStyle:NSDateFormatterFullStyle];
            [gmtFormatter setTimeStyle:NSDateFormatterFullStyle];
            [gmtFormatter setTimeZone:[NSTimeZone timeZoneWithName:@"GMT"]];
    
            return [gmtFormatter dateFromString:dateString];
        }
    
        - (NSDate *)convertIntoSystemZoneDate:(NSString *)dateString
        {
            NSDateFormatter *systemZoneFormatter = [[NSDateFormatter alloc]init];
            [systemZoneFormatter setDateStyle:NSDateFormatterFullStyle];
            [systemZoneFormatter setTimeStyle:NSDateFormatterFullStyle];
            [systemZoneFormatter setTimeZone:[NSTimeZone systemTimeZone]];
    
            return [systemZoneFormatter dateFromString:dateString];
        }