我想要给定数字的星期几名称,这是伪代码:
getDayStringForInt:0 = sunday
getDayStringForInt:1 = monday
getDayStringForInt:2 = tuesday
getDayStringForInt:3 = wenesday
getDayStringForInt:4 = thursday
getDayStringForInt:5 = friday
getDayStringForInt:6 = saturday
我试过下面的代码,但有些东西不工作......
- (void) setPeriodicityDayOfWeek:(NSNumber *)dayOfWeek{
gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
dateFormatter = [[NSDateFormatter alloc] init];
NSLocale *frLocale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US"];
[dateFormatter setLocale:frLocale];
[gregorian setLocale:frLocale];
NSDate *today = [NSDate date];
NSDateComponents *nowComponents = [gregorian components:NSYearCalendarUnit | NSWeekCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit fromDate:today];
[nowComponents setWeekday:dayOfWeek];
NSDate *alertDate = [gregorian dateFromComponents:nowComponents];
[dateFormatter setDateFormat:@"EEEE"];
NSLog(@"Day Of Week : %@ - Periodicity : %@", dayOfWeek, [dateFormatter stringFromDate:alertDate]);
alert.periodicity = [dateFormatter stringFromDate:alertDate];
我的日志很奇怪:
Day Of Week : 0 - Periodicity : monday
Day Of Week : 1 - Periodicity : wenesday
Day Of Week : 2 - Periodicity : friday
Day Of Week : 3 - Periodicity : friday
Day Of Week : 4 - Periodicity : tuesday
Day Of Week : 5 - Periodicity : sunday
Day Of Week : 6 - Periodicity : sunday
有什么想法吗?任何更好的解决方案......
最佳答案
由于这已成为公认的答案,我也将在此处发布“正确”的解决方案。归功于 Rob 的回答。
整个事情可以简单地使用 NSDateFormatter
的 [shortWeekdaySymbols][1]
方法来实现,所以完整的解决方案归结为
- (NSString *)stringFromWeekday:(NSInteger)weekday {
NSDateFormatter * dateFormatter = [NSDateFormatter new];
dateFormatter.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US"];
return dateFormatter.shortWeekdaySymbols[weekday];
}
原始答案
请注意,您正在将指向 NSNumber
的指针传递给需要 NSInteger
的方法。
编译器不会警告您,因为指针确实是一个整数,只是不是您所期望的那样。
考虑这个简单的测试:
- (void)foo:(NSInteger)a {
NSLog(@"%i", a);
}
- (void)yourMethod {
[self foo:@1]; // @1 is the boxed expression for [NSNumber numberWithInt:1]
}
这会打印类似 185035664
的内容,它是指针值,即转换为 NSInteger
时的 NSNumber *
。
您应该在方法签名中使用 [dayOfWeek integerValue]
或直接将 dayOfWeek
转换为 NSInteger
。
此外,我认为您还有其他错误:来自 setWeekday:
Sets the number of weekday units for the receiver. Weekday units are the numbers 1 through n, where n is the number of days in the week. For example, in the Gregorian calendar, n is 7 and Sunday is represented by 1.
星期日是1,你最好也和你的代理核对一下。
关于objective-c - 如何从给定的数字中获取星期几,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18316614/