views:

116

answers:

1

Hi all! I am newbie of objective-c and i got this crazy problem…

for low precision test case:

dateString = @"2010-05-25 11:05:21", conversion success.

dateString = @"2010-03-01 15:54:36", conversion fail.

for high precision test case:

dateString = @"2010-05-25 11:05:21.937113", conversion success.

dateString = @"2010-03-01 15:54:36.937113", conversion fail.

below is my code:

// Date formatter
 NSLocale *locale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US"];
 NSDateFormatter *dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
 [dateFormatter setFormatterBehavior:NSDateFormatterBehavior10_4];
 [dateFormatter setDateFormat:@"yyyy-MM-dd hh:mm:ss.SSSSSS"];
 [dateFormatter setLocale:locale];

NSDateFormatter *lowPrecisionDateFormatter = [[[NSDateFormatter alloc] init] autorelease];
[lowPrecisionDateFormatter setFormatterBehavior:NSDateFormatterBehavior10_4];
[lowPrecisionDateFormatter setDateFormat:@"yyyy-MM-dd hh:mm:ss"];
[lowPrecisionDateFormatter setLocale:locale];

// try high precision first, if fail, then go ahead to low precision. 
NSDate *date = [dateFormatter dateFromString:dateString];
if(!date){
  date = [lowPrecisionDateFormatter dateFromString:dateString];
}

Any help is highly appreciated!!

+2  A: 

This is just a guess, but I think it has to do with using a 24-hour day format rather than AM and PM. I believe if you use HH rather than hh in your setDateFormat string that it should work.

Edit:

Actually, I'm pretty confident that this is it after looking at this blog posting.

Justin Peel
thanks mate, overnight work really makes me lost focus! :(
sunnycmf