Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to turn a NSString into NSDate?

Ive been racking my brains with no luck. Could someone please tell me how i would convert this string:

"2011-01-13T17:00:00+11:00"

into a NSDate?

like image 913
jennas Avatar asked Jan 13 '11 12:01

jennas


1 Answers

The unicode date format doc is here

Also, for your situation, you could try this:

// original string
NSString *str = [NSString stringWithFormat:@"2011-01-13T17:00:00+11:00"];

// convert to date
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
// ignore +11 and use timezone name instead of seconds from gmt
[dateFormat setDateFormat:@"YYYY-MM-dd'T'HH:mm:ss'+11:00'"];
[dateFormat setTimeZone:[NSTimeZone timeZoneWithName:@"Australia/Melbourne"]];
NSDate *dte = [dateFormat dateFromString:str];
NSLog(@"Date: %@", dte);

// back to string
NSDateFormatter *dateFormat2 = [[NSDateFormatter alloc] init];
[dateFormat2 setDateFormat:@"YYYY-MM-dd'T'HH:mm:ssZZZ"];
[dateFormat2 setTimeZone:[NSTimeZone timeZoneWithName:@"Australia/Melbourne"]];
NSString *dateString = [dateFormat2 stringFromDate:dte];
NSLog(@"DateString: %@", dateString);

[dateFormat release];
    [dateFormat2 release];

Hope this helps.

like image 148
tbone Avatar answered Oct 03 '22 23:10

tbone