Reputation: 621
I wonder how could I make a list of days from MONDAY to SUNDAY...
I did it so:
- (NSString *) stringWithDayNameOf:(int)day {
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:@"D"];
NSDate *date = [dateFormat dateFromString:[NSString stringWithFormat:@"%i", day]];
[dateFormat setDateFormat:@"eeee"];
NSString* outer = [dateFormat stringFromDate:date];
outer = [outer uppercaseString];
return outer;
}
for (int i = 1; i <= 7; i++) {
NSLog(@"DAY: %@", [self stringWithDayNameOf:i]);
}
But it displays days from today... How to fix that or make simpler?
Thanks!!
Upvotes: 1
Views: 779
Reputation: 64002
%D
is the format specifier for "day of year", not "day of week". There's no specifier for numerical day of week, since (as far as I know) no-one writes dates that way.
You need to create your date using NSDateComponents
and then format that:
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:@"eeee"];
NSCalendar * cal = [NSCalendar currentCalendar];
NSUInteger numWeekdays = [cal maximumRangeOfUnit:NSWeekdayCalendarUnit].length;
NSDateComponents * comp = [[NSDateComponents alloc] init];
for( NSUInteger day = 1; day <= numWeekdays; day++ ){
[comp setWeekday:day];
[comp setWeek:0];
NSDate * date = [cal dateFromComponents:comp];
NSString * dayName = [dateFormat stringFromDate:date];
NSLog(@"%@", dayName);
}
Also, NSDateFormatter
knows the names of the days of the week already: -[NSDateFormatter weekdaySymbols]
. The first day of the week in the Gregorian calendar is Sunday.
Upvotes: 2
Reputation: 53000
Use NSDateFormatter
's weekdaySymbols
and friends (for short names etc.)
Upvotes: 5