简体   繁体   中英

NSDateFormatter and Region Format Weekday

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?

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.

- (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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM