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?
On iOS 7 and later NSDateFormatter is thread safe. In macOS 10.9 and later NSDateFormatter is thread safe so long as you are using the modern behavior in a 64-bit app.
I created a method that is supposed to take in a string in "YYYY-MM-DD" form and spit out an int that represents the dates position in relation to the week it is in (regardless if it overlaps between months). So e.g sunday=1 monday=2 and so on.
Try this code: let dateFormatterGet = NSDateFormatter() dateFormatterGet. dateFormat = "yyyy-MM-dd HH:mm:ss" let dateFormatterPrint = NSDateFormatter() dateFormatterPrint. dateFormat = "MMM dd,yyyy" let date: NSDate?
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]];
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With