NsDate formatter giving wrong Date from String [duplicate]

情到浓时终转凉″ 提交于 2019-11-28 09:57:42

问题


This question already has an answer here:

  • NSDate Format outputting wrong date 5 answers

I have the following code which takes a NSString and returns NSDate. I have copied this code from a project in which it runs perfectly fine - but some how this gives me the wrong output

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

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

    return [dateFormatter dateFromString:date];
}

and the output is from logs:

Date: 07-01-2014 Formatted: 2014-01-06 18:30:00 +0000
Date: 24-01-2014 Formatted: 2014-01-23 18:30:00 +0000
Date: 06-01-2014 Formatted: 2014-01-05 18:30:00 +0000
Date: 15-01-2014 Formatted: 2014-01-14 18:30:00 +0000
Date: 22-01-2014 Formatted: 2014-01-21 18:30:00 +0000
Date: 31-01-2014 Formatted: 2014-01-30 18:30:00 +0000
Date: 14-01-2014 Formatted: 2014-01-13 18:30:00 +0000
Date: 30-01-2014 Formatted: 2014-01-29 18:30:00 +0000

In a weird sense it is also changing the Date..!! Any help...!!!


回答1:


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];
}



回答2:


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;
}


来源:https://stackoverflow.com/questions/21180922/nsdate-formatter-giving-wrong-date-from-string

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