I am developing an app for the iPhone where I need to convert an date from an XML feed into just a HH:MM format.
I have the following method that doesn't work and I have no clue what I am doing wrong.
As an example, the timeToConvert string would be: "Mon, 01 Feb 2010 21:55:00 +0100" (without the quotes)
The method works when the region is set to US (I get back the correct date), but not when I change the region (in Settings->General->International) to Spain, or other regions (in that case I get back nil).
- (id)timeConvertToHHMM:(NSString *)timeToConvert {
NSString *newPubDate = timeToConvert;
//Let's remove any rubbish from the code
newPubDate = [newPubDate stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
//create formatter and format to convert the XML string to an NSDate
NSDateFormatter *originalDateFormatter = [[[NSDateFormatter alloc] init] autorelease];
[originalDateFormatter setDateFormat:@"EEE, d MMM yyyy H:mm:ss z"];
//run the string through the formatter
NSDate *formattedDate = [[NSDate alloc] init];
formattedDate = [originalDateFormatter dateFromString:newPubDate];
//Let's now create another formatter to take the NSDate and convert format it to Hours and minutes
NSDateFormatter *newDateFormatter = [[[NSDateFormatter alloc] init] autorelease];
[newDateFormatter setDateFormat:@"HH:mm"]; // 24H clock set
// And let's convert it back to a readable string
NSString *calcHHMM = [newDateFormatter stringFromDate:formattedDate];
开发者_JAVA技巧 NSLog(@"CalcHHMM: %@", calcHHMM);
return calcHHMM;
}
Any hint on why this is not working, and just returning NULL will be more than welcome.
Problem appears to be your region setting is not "en-US" so the date formatter doesn't parse the string using the en-US format supplied. Although there may be a more elegant, general solution, doing a setLocale on originalDateFormatter to en_US can be used as a workaround to solve the problem.
As you've already tried in your code:
[originalDateFormatter setLocale:[[[NSLocale alloc] initWithLocaleIdentifier:@"en_US"] autorelease]];
I had the exact same issue. My problem was that my initial date string had a single millisecond character:
Example: 2011-02-06 08:13:22:1
and was being parsed with this format :[formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
The iPhone simulator was forgiving and successfully parsed the date with the milliseconds, however when building to my iphone it did not.
Changing the formatter to: [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss.S"];
solved the problem.
精彩评论