Reputation: 2809
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?
Upvotes: 5
Views: 9963
Reputation: 5634
The accepted answer doesn't really address the asked question. Just like Hot Licks commented, it's possible to set the (standard/short/long/etc) weekday/month symbols on the DateFormatter instance:
dateFormatter.shortWeekdaySymbols = dateFormatter.shortWeekdaySymbols.map { $0.localizedUppercase }
dateFormatter.monthSymbols = dateFormatter.monthSymbols.map { $0.localizedCapitalized }
If you need to set your formatter's locale to other than the default you should make these calls after doing so.
Upvotes: 9
Reputation: 318814
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]];
Upvotes: 10
Reputation: 58448
Just get the day on its own, uppercase it, then get the rest of the date and append it. Like so:
[dateFormat setFormat:@"EEE"];
NSString *day = [dateFormat stringFromDate:today];
[dateFormat setFormat:@"MMM. dd"];
NSString *restOfDate = [dateFormat:stringFromDate:today];
NSString *fullDate = [[day uppercaseString] stringByAppendingFormat:@", %@", restOfDate];
Upvotes: 1