Pergunta

I got a problem with NSDateFormatter with different regions.

I'm retrieving a string from the database with the weekday.

//wdn is 0 for sunday //1 monday //2 ..
NSString *wd = [NSString stringWithFormat:@"%i",wdn];

then I'm formatting the string to have the weekday in letters:

NSDateFormatter *dateFormat = [[NSDateFormatter alloc]init];
[dateFormat setDateFormat:@"c"];
NSDate *d = [dateFormat dateFromString:wd];
[dateFormat setDateFormat:@"ccc"];

results:

//with UK region in settings //RIGHT
//0 SUN //1 MON //2 ..

//with US region in settings //WRONG
//0 MON //1 TUE //3..

How can I force to have the right result no matter which region I choose?

Foi útil?

Solução

If you're just trying to map 0 -> the locale's version of "Sun", you can use -[NSDateFormatter shortWeekdaySymbols].

The documentation doesn't have any description of the ordering, but I've tried with en_US/he_IL for Sunday first and en_UK/fr_FR for Monday first. In all cases the array returns the locale equivalent of @[@"Sun", @"Mon", ...] with Sunday being the first day.

Of course, your code may become invalid if you assume the locale is using a gregorian calendar, but that's really outside the scope of the question as that probably relates more to the design of the app as a whole.

Outras dicas

- (NSString *)stringWithDayOfWeek:(NSUInteger)dayOfWeek length:(NSUInteger)length
{
    NSDictionary *days = @{
        @0: @"Monday",
        @1: @"Tuesday",
        // etc...
    };

    NSString *dayOfWeekStringRepresentation = days[[NSNumber numberWithInteger:dayOfWeek]];
    dayOfWeekStringRepresentation = [dayOfWeekStringRepresentation substringWithRange:NSMakeRange(0, length)];

    return dayOfWeekStringRepresentation;
}
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top