NsDate formatter giving wrong Date from String [du

2019-01-28 17:12发布

This question already has an answer here:

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...!!!

2条回答
Animai°情兽
2楼-- · 2019-01-28 17:57

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;
}
查看更多
小情绪 Triste *
3楼-- · 2019-01-28 18:08

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];
}
查看更多
登录 后发表回答