objective c - From string with locale to date on iphone sdk -
i trying find way convert string date given locale identifier. have example italian date (locale: it_it) want convert valid date object.
nsdate *gldatewithstring(nsstring *string, nsstring *localeidentifier) { [nsdateformatter setdefaultformatterbehavior:nsdateformatterbehavior10_4]; nsdateformatter *formatter = [[nsdateformatter alloc] init]; nslocale *locale = [[nslocale alloc] initwithlocaleidentifier:localeidentifier]; [formatter setlocale:locale]; [locale release]; nsdate *date = [formatter datefromstring:string]; [formatter release]; return date; }
this code not work, date nil. can't figure out how should use locale setting purpose.
the solution use getobjectvalue:forstring:range:error: method of nsdateformatter , set correct date , time style ad follow:
- (nsdate *)datewithstring:(nsstring *)string locale:(nsstring *)localeidentifier { nsdateformatter *formatter = [[nsdateformatter alloc] init]; [formatter settimestyle:nsdateformatternostyle]; [formatter setdatestyle:nsdateformattershortstyle]; nslocale *locale = [[nslocale alloc] initwithlocaleidentifier:localeidentifier]; [formatter setlocale:locale]; [locale release]; nsdate *date = nil; nsrange range = nsmakerange(0, [string length]); nserror *error = nil; bool converted = no; converted = [formatter getobjectvalue:&date forstring:string range:&range error:&error]; [formatter release]; return converted? date : nil; }
example:
nsstring *italiandate = @"30/10/2010"; nsstring *italianlocale = @"it_it"; nsdate *date = [mycustomformatter datewithstring:italiandate locale:italianlocale];
Comments
Post a Comment