From string with locale to date on iphone sdk

柔情痞子 提交于 2020-01-25 04:39:28

问题


I trying to find a way to convert a string into a date with a given locale identifier. I have for example an italian date (locale: it_IT) I want to convert into a 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 does not work, the date is nil. I can't figure out how I should use the locale setting for my purpose.


回答1:


The solution is to use getObjectValue:forString:range:error: method of NSDateFormatter and set the correct date and 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];



回答2:


I struggled with German formats as well sometime ago and solved the problem by supplying my own formatting string:

[formatter setDateFormat:@"dd.MMM.yyyy HH:mm:ss"];

Then:

[dateFormatter dateFromString:@"01.Dez.2010 15:03:00"];

will get a correct NSDate.



来源:https://stackoverflow.com/questions/4334871/from-string-with-locale-to-date-on-iphone-sdk

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!