NSDateFormatter dateFromString conversion

2019-09-19 09:16发布

问题:

I am having problems with conversion of NSString object to NSDate. Here is what I want to do: I am downloading an RSS Message from the internet. I have the whole message parsed by NSXMLParser. After that, I have parts like , or saved to particular NSStrings. I want to convert element (that includes publication date of RSS Message) to NSDate so that I could perform some operations on it like on a date object (e.g. sorting, showing on a clock etc.). Here is the way my looks like:

"Wed, 25 Sep 2013 12:56:57 GMT"

I tried to convert it to NSDate in this way:

*//theString is NSString containing my date as a text
NSDate *dateNS = [[NSDate alloc] init];
        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
        [dateFormatter setDateFormat:@"EEE, dd MMM yyyy hh:mm:ss ZZZ"];
dateNS = [dateFormatter dateFromString:theString];*

However, after doing above code, dateNS always appear to be (null).

My question is simple: what is the right way to convert NSString with date formatted like this to NSDate object?

By the way, I have seen the website http://www.unicode.org/reports/tr35/tr35-25.html#Date_Format_Patterns It seems that there are many ways to format particular date, but I could not find what I am doing wrong.

回答1:

Your problem is the your date formatter has not identical fort as your date string: You should set date formatter the same format like your date string

My Example:

// Convert string to date

    NSString *beginString = @"Sat, 30 Dec 2013 14:45:00 EEST";
    //beginString = [beginString stringByReplacingOccurrencesOfString:@"EEST" withString:@""];
    //beginString = [beginString stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];

    dateFormat = [[NSDateFormatter alloc] init];
    [dateFormat setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"en_GB"]];
    [dateFormat setTimeZone:[NSTimeZone timeZoneWithName:@"Europe/Helsinki"]];
    [dateFormat setDateFormat:@"EEE, dd MMM yyyy HH:mm:ss z"];
    dateFromString = [dateFormat dateFromString:beginString];

    //NSLog(@"Begin string: %@", beginString);

    //NSLog(@"not formated: %@", dateFromString);

    // Convert Date to string

    [dateFormat setTimeZone:[NSTimeZone localTimeZone]];
    [dateFormat setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"ru_RU"]];
    [dateFormat setDateFormat:@"dd MMMM yyyy"];
    myStrDate = [dateFormat stringFromDate:dateFromString];
    [currentTitle setPubDate:myStrDate];


回答2:

NSDate * dateNS = [[NSDate alloc] init]; is useless, you don't need to allocate any date object.

NSDateFormatter * dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"EEE, dd MMM yyyy HH:mm:ss ZZZ"];
NSLog(@"%@", [dateFormatter dateFromString:@"Wed, 25 Sep 2013 12:56:57 GMT"]);

Outputs the date correctly, are you sure theString isn't nil?