How do I get weekday and/or name of month from a NSDate variable?
Simple Swift 3 extensions:
// Weekday
extension Date {
func dayOfWeek() -> String? {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "EEEE"
return dateFormatter.string(from: self).capitalized
// or capitalized(with: locale)
}
}
print(Date().dayOfWeek()!) // Wednesday
// Month Name
extension Date {
func monthName() -> String? {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "MMMM"
return dateFormatter.string(from: self).capitalized
// or capitalized(with: locale)
}
}
print(Date().monthName()!) // October
There is no need to manually convert to the Swedish words. iPhone will do it for you. Try this:
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
dateFormatter.dateFormat = @"yyyyMMdd";
NSDate *date = [dateFormatter dateFromString:@"20111010"];
// set swedish locale
dateFormatter.locale=[[NSLocale alloc] initWithLocaleIdentifier:@"sv_SE"];
dateFormatter.dateFormat=@"MMMM";
NSString *monthString = [[dateFormatter stringFromDate:date] capitalizedString];
NSLog(@"month: %@", monthString);
dateFormatter.dateFormat=@"EEEE";
NSString *dayString = [[dateFormatter stringFromDate:date] capitalizedString];
NSLog(@"day: %@", dayString);
Output:
month: Oktober
day: Måndag
NSString *strDate=@"20110407";
NSDateFormatter *df=[[[NSDateFormatter alloc] init] autorelease];
[df setDateFormat:@"yyyyMMdd"];
NSDate *targetDate=[df dateFromString:strDate];
[df setDateFormat:@"EEEE MMMM dd, yyyy"];
NSString *s=[df stringFromDate:targetDate];
NSLog(@"Date: %@", s);