Convert NSString to NSDate

21,174

Solution 1

It's a simple one, converting NSString to NSDate we use NSDateformatter using dateFromString method. We need to provide the Dateformatter style with existing style for NSString

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ssZ"];
NSDate *date = [dateFormatter dateFromString:@"2013-02-01T06:25:47Z"];
NSTimeZone *pdt = [NSTimeZone timeZoneWithAbbreviation:@"PDT"];
[dateFormatter setTimeZone:pdt];
[dateFormatter setDateFormat:@"HH:mm:ss zzz"];
[dateFormatter setDateFormat:@"K:mm a, z"];
NSString * updated String = [dateFormatter stringFromDate:date];

Solution 2

You can use below function:

-(NSDate *)getDateFromString:(NSString *)pstrDate
{
    NSDateFormatter *df1 = [[[NSDateFormatter alloc] init] autorelease];
    [df1 setDateFormat:@"yyyy-MM-dd'T'HH:mm:ssZ"];
    NSDate *dtPostDate = [df1 dateFromString:pstrDate];
    return dtPostDate;
}

Hope, it will be helpful to you.

This function will accept your string date and return the NSDate value.

Cheers!

Share:
21,174
vivianaranha
Author by

vivianaranha

Updated on July 11, 2022

Comments

  • vivianaranha
    vivianaranha almost 2 years

    Possible Duplicate:
    Converting NSString to NSDate (and back again)

    I make a request to the flickr api and it returns me the date in the following format

    "2013-02-01T06:25:47Z"
    

    How do i convert this into NSDate format??