How to turn a NSString into NSDate?

2019-03-21 10:08发布

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条回答
冷血范
2楼-- · 2019-03-21 10:35

Did you try this

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

Cheers

查看更多
虎瘦雄心在
3楼-- · 2019-03-21 10:35

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"];
查看更多
Lonely孤独者°
4楼-- · 2019-03-21 10:40

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"]];
查看更多
疯言疯语
5楼-- · 2019-03-21 10:43

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.

查看更多
Juvenile、少年°
6楼-- · 2019-03-21 10:55

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!

查看更多
登录 后发表回答