How to turn a NSString into NSDate?

后端 未结 5 1314
攒了一身酷
攒了一身酷 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.

    0 讨论(0)
  • 2021-02-10 11:23

    put the T part in single quotes, and check the unicode docs for the exact formatting. In my case, I have something similar, which I do this:

    NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
            [dateFormat setDateFormat:@"YYYY-MM-dd'T'HH:mm:ss.SSS"];
    

    Again, not exactly the same, but you get the idea. Also, be careful of the timezones when converting back and forth between strings and nsdates.

    Again, in my case, I use:

    [dateFormat setTimeZone:[NSTimeZone timeZoneWithName:@"America/New_York"]];
    
    0 讨论(0)
  • 2021-02-10 11:31

    You might check out TouchTime.

    https://github.com/jheising/TouchTime.

    It's a direct port of the awesome strtotime function in PHP in 5.4 for Cocoa and iOS. It will take in pretty much any arbitrary format of date or time string and convert it to an NSDate.

    Hope it works, and enjoy!

    0 讨论(0)
  • 2021-02-10 11:36

    Try using this cocoapods enabled project. There are many added functions that will probably be needed as well.

    "A category to extend Cocoa's NSDate class with some convenience functions."

    https://github.com/billymeltdown/nsdate-helper

    Here's an example from their page:

    NSDate *date = [NSDate dateFromString:@"2009-03-01 12:15:23"];
    
    0 讨论(0)
  • 2021-02-10 11:37

    Did you try this

    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    NSDate *dateT = [dateFormatter dateFromString:str];
    

    Cheers

    0 讨论(0)
提交回复
热议问题