How to turn a NSString into NSDate?

不想你离开。 提交于 2019-12-21 02:54:06

问题


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?


回答1:


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.




回答2:


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"]];



回答3:


Did you try this

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

Cheers




回答4:


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!




回答5:


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"];


来源:https://stackoverflow.com/questions/4680228/how-to-turn-a-nsstring-into-nsdate

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!