简体   繁体   中英

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.

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

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

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 :)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM