开发者

NSDate from NSString

I've read the DateFormatting guide and I'm still not able to get a working formatter.

NSString *string = @"0901Z 12/17/09";   
//This is a sample date. The Z stands for GMT timezone
//The 0901 is 09h 01m on a 24 hour clock not 12.
//As long as I can get the hours/min & date from the string I can deal with the time zone later
NSDa开发者_如何学运维teFormatter *dateFormat = [[NSDateFormatter alloc] init]; 
[dateFormat setDateFormat:@"hhmm'Z' MM/dd/yy"];
NSDate *date = [dateFormat dateFromString:string];


That works for me when I try it. Adding NSLog(@"%@", date) to the end of your code gives me this output:

2010-02-28 12:17:22.921 app[9204:a0f] 2009-12-17 09:01:00 -0800

What is the problem you're seeing?

Edit: I figured it out, you're not having a problem with 09:01, but with other 24-hour times, like 14:25, right? Change your formatter to:

@"HHmm'Z' MM/dd/yy"


Copied from a similar question I answered here: NSDateFormatter returns nil for @"dd-MM-yy" in iOS 3.0

If you're working with user-visible dates, you should avoid setting a date format string. Formatting dates this way is not localizable and makes it impossible to predict how your format string will be expressed in all possible user configurations. Rather, you should try and limit yourself to setting date and time styles (via -[NSDateFormatter setDateStyle:] and -[NSDateFormatter setTimeStyle:]).

On the other hand, if you're working with fixed-format dates, you should first set the locale of the date formatter to something appropriate for your fixed format. In most cases the best locale to choose is "en_US_POSIX", a locale that's specifically designed to yield US English results regardless of both user and system preferences. "en_US_POSIX" is also invariant in time (if the US, at some point in the future, changes the way it formats dates, "en_US" will change to reflect the new behaviour, but "en_US_POSIX" will not), and between machines ("en_US_POSIX" works the same on iPhone OS as it does on Mac OS X, and as it it does on other platforms).

Once you've set "en_US_POSIX" as the locale of the date formatter, you can then set the date format string and the date formatter will behave consistently for all users.

The above info and more can be found in Apple's Technical Q&A QA1480

Here's a snippet of code from my app which implements the above recommendation :

static NSDateFormatter* dateFormatter = nil;
if (!dateFormatter) {
dateFormatter = [[NSDateFormatter alloc] init];
NSLocale *enUSPOSIXLocale = [[[NSLocale alloc] 
             initWithLocaleIdentifier:@"en_US_POSIX"] autorelease];
NSAssert(enUSPOSIXLocale != nil, @"POSIX may not be nil.");
[dateFormatter setLocale:enUSPOSIXLocale];
[dateFormatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];

dateFormatter.dateFormat = @"EEE, dd MMM yyyy HH:mm:ss +0000";
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜