NsDate formatter giving wrong Date from String [duplicate]

谁说胖子不能爱 提交于 2019-11-29 16:06:51

The results are formated for GMT output - i.e. if you are 5:3 hours away from GMT.

You need to specify a timezone if you want the date formated to be returned in that timezone: (that is what the +0000 means)

- (NSDate *)dateFromString:(NSString *)date
{
    static NSDateFormatter *dateFormatter;
    if (!dateFormatter)
    {
        dateFormatter = [[NSDateFormatter alloc] init];
        [dateFormatter setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"]];
        [dateFormatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];
        [dateFormatter setDateFormat:@"dd-MM-yyyy"];
    }

    NSLog(@"Date: %@ Formatted: %@",date,[dateFormatter dateFromString:date]);

    return [dateFormatter dateFromString:date];
}

Check this

- (NSDate *)dateFromString:(NSString *)date
{
    static NSDateFormatter *dateFormatter;
    if (!dateFormatter)
    {
        dateFormatter = [[NSDateFormatter alloc] init];
        [dateFormatter setDateFormat:@"dd-MM-yyyy"];
    }
    NSDate *dateValue= [dateFormatter dateFromString:date];
    NSLog(@"Date: %@ Formatted: %@",date,[dateFormatter stringFromDate:dateValue]);

    return dateValue;
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!