From the current locale string on iphone sdk

I am trying to find a way to convert a string to a date with the given locale id. I have, for example, an Italian date (locale: it_IT). I want to convert to 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 zero. I cannot figure out how I should use the locale settings for my purpose.

+1
source share
2 answers

The solution is to use the getObjectValue: forString: range: error: method of NSDateFormatter and set the correct date and time style declaration:

- (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];
+1
source

, -, , :

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

:

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

NSDate.

0

Source: https://habr.com/ru/post/1779346/


All Articles