How to turn a NSString into NSDate?

后端 未结 5 1475
攒了一身酷
攒了一身酷 2021-02-10 10:50

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?

5条回答
  •  夕颜
    夕颜 (楼主)
    2021-02-10 11:19

    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.

提交回复
热议问题