简体   繁体   中英

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?

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.

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

Did you try this

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

Cheers

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!

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM