user831679
user831679

Reputation:

convert date string to NSDate in objective c/iOS

I have this string ----> Sun, 16 Dec 2012 15:30:22 +0000

I want to convert it to NSDate. I have tried the below code but it is giving me null

NSDateFormatter *df = [[NSDateFormatter alloc] init];

[df setDateFormat:@"yyyy-MM-dd hh:mm:ss a"];

NSDate *date = [[NSDate alloc] init];

date = [df dateFromString: @"Sun, 16 Dec 2012 15:30:22 +0000"];

NSLog(@"date: %@", date);

I am not getting the issue ?

Any guidance plz

Upvotes: 11

Views: 17109

Answers (3)

Satish Azad
Satish Azad

Reputation: 2312

Try this to get NSDate from String

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

    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setLocale:[[[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"] autorelease]];
    //[dateFormatter setDateFormat:@"YYYY-MM-dd HH:mm:ss a"];
    [dateFormatter setDateFormat:@"EEE, dd MMM yyyy HH:mm:ss ZZZ"];
    [dateFormatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];

    NSLog(@"%@", aStr);
    NSDate   *aDate = [dateFormatter dateFromString:aStr];
    [dateFormatter release];
    return aDate;
}

It works fine for me.

Upvotes: 2

Paul.s
Paul.s

Reputation: 38728

The dateFormat of the formatter needs to match the format of the string you are providing it with.

Therefore something like this should work

NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
formatter.dateFormat = @"EEE, dd MMM yyyy HH:mm:ss ZZZ";

NSLog(@"%@", [formatter dateFromString:@"Fri, 18 Jan 2013 15:30:22 +0000"]);

To look up what the specifiers actually mean check Unicode Technical Standard #35

Upvotes: 13

P.J
P.J

Reputation: 6587

Try this code

NSDateFormatter *df = [[NSDateFormatter alloc] init];

    [df setDateFormat:@"EEEE, dd MMM yyyy"];

    NSDate *date = [[NSDate alloc] init];

    date = [df dateFromString: @"Sun, 16 Dec 2012"];

    NSLog(@"date: %@", date);

Hope it helps you..

EDIT :-

For your string

NSDateFormatter *df = [[NSDateFormatter alloc] init];

    [df setDateFormat:@"EEEE, dd MMM yyyy HH:mm:ss z"];

    NSDate *date = [[NSDate alloc] init];

    date = [df dateFromString: @"Sun, 16 Dec 2012 15:30:22 +0000"];

    NSLog(@"date: %@", date);

Upvotes: 3

Related Questions