Search code examples
iosnsdatensdateformatter

Trying to capitalize abbreviated day of the week in NSDateFormatter object in iOS


I am working on an application in iOS where I have an NSDateFormatter object as follows:

NSDate *today = [NSDate date];
 NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
 [dateFormat setDateFormat:@"EEE, MMM. dd"];
 NSString *dateString = [dateFormat stringFromDate:today];
 NSLog(@"%@", dateString);

My output is: Tue, Dec. 10 and I would like to display: TUE, Dec. 10 instead.

My problem though is that the day of the week has only the first letter capitalized, and not the entire day (i.e. I am getting "Tue", and I would like to display "TUE"). The formatting of the month is fine (i.e. "Dec" I am happy with).

I have checked the specs on date formatting and unfortunately there is no conventional way of doing this using the NSDateFormatter class. Is there a way around this to still capitalize all of the abbreviated letters in the day of the week only without touching the month?


Solution

  • There is no way to do this directly with the date formatter. The easiest would be to process the string after formatting the date.

    NSString *dateString = [dateFormat stringFromDate:today];
    dateString = [NSString stringWithFormat:@"%@%@", [[dateString substringToIndex:3] uppercaseString], [dateString substringFromIndex:3]];
    

    Update:

    The above assumes that EEE always gives a 3-letter weekday abbreviation. It may be possible that there is some locale or language where this assumption isn't valid. A better solution would then be the following:

    NSString *dateString = [dateFormat stringFromDate:today];
    NSRange commaRange = [dateString rangeOfString:@","];
    dateString = [NSString stringWithFormat:@"%@%@", [[dateString substringToIndex:commaRange.location] uppercaseString], [dateString substringFromIndex:commaRange.location]];