user1988
user1988

Reputation: 811

NSString to NSDate conversion using NSDateformatter

I have a string of date 2010-11-29T00:00:00+05:30 and I want to convert it into NSDate. I want to convert it into 11/29/2010. For this I am doing something like this..

NSDateFormatter *df = [[NSDateFormatter alloc] init];
textForLabel = @"2010-11-29T00:00:00+05:30";
[df setDateFormat:@"yyyy-MM-dd"];
NSDate *myDate = [df dateFromString:textForLabel];
NSLog(@"date : %@",myDate);

But output is null.

What could be date format for 2010-11-29T00:00:00+05:30 ?

I am not getting what is getting wrong here.

Upvotes: 0

Views: 560

Answers (4)

Ananth
Ananth

Reputation: 845

-(NSDate *) getDateFor :(NSString *)ICSDateString
{
    int strLen = [ICSDateString length];    
    NSString * subString1 = [ICSDateString substringWithRange:NSMakeRange(0, strLen - 1)];
    NSLog(@"%d  %d subString1 %@", strLen, subString1.length, subString1);
    NSDateFormatter* df = [[NSDateFormatter alloc] init];
    [df setDateFormat:@"yyyyMMdd'T'HHmmss'Z'"];
    [df setLocale:[[[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"] autorelease]];

    NSDate* parsedDate = [df dateFromString:subString1];

    [df release];
    NSLog(@"parsedDate %@", parsedDate);
    return parsedDate;
}

Think, this is the correct way to get NSDate from a ICS formatted date. Have a look at this link for reference. Thanks.

Upvotes: 0

poncha
poncha

Reputation: 7856

First, get rid of colon in the timezone, as there is no timezone format identifier for '+05:30'

textForLabel = [textForLabel
                stringByReplacingCharactersInRange:NSMakeRange(21,1)
                withString:@""];

Then, you will have this string: 2010-11-29T00:00:00+0530

The following date format can be used:

[df setDateFormat:@"yyyy:MM:dd'T'HH:mm:sszzz"];

Related question: iPhone NSDateFormatter Timezone Conversion

Upvotes: 1

rakeshNS
rakeshNS

Reputation: 4257

Try this,

NSDateFormatter *df = [[NSDateFormatter alloc] init];
textForLabel = @"2010-11-29T00:00:00+05:30";
NSArray *components = [textForLabel componentsSeperatedByString:@"T"];
[df setDateFormat:@"yyyy-MM-dd"];
NSDate *myDate = [df dateFromString:[components objectAtIndex:0]];
NSLog(@"date : %@",myDate);

This is not the desired method, but will work :)

Upvotes: 0

Caleb
Caleb

Reputation: 124997

textForLabel = 2010-11-29T00:00:00+05:30

That's not a string. I doubt it'll even compile, given the lack of an ending semicolon, but if it does the compiler is probably interpreting it as an expression and assigning the resulting number to textForLabel. To make it a string, do this:

textForLabel = @"2010-11-29T00:00:00+05:30";

Upvotes: 0

Related Questions