【发布时间】:2013-12-13 02:23:01
【问题描述】:
我知道有一些与此类似的问题,但我就是找不到我的代码有什么问题。
基本上我想要的是如果今天不是星期天, currentDate 设置为最后一个星期天。 如果今天是星期天,我将 currentDate 设置为之前的星期天。
这就是我的尝试。
NSDateComponents *components = [[NSCalendar currentCalendar] components: NSWeekCalendarUnit | NSYearCalendarUnit | NSWeekdayCalendarUnit fromDate:currentDate];
if (components.weekday == 1) { //Its sunday. We just need to subtract a week
[components setWeek: -1];
currentDate = [[NSCalendar currentCalendar] dateByAddingComponents:components toDate:currentDate options:0];
}else{ //If its not sunday we just go to sunday
[components setWeekday: 1];
currentDate = [[NSCalendar currentCalendar] dateFromComponents:components];
}
第一次执行这部分代码时,我得到了正确的答案。在我第一次得到奇怪的日期之后,比如 4026 年 12 月 2 日,并且年份不断增加。
这是使它工作的代码:
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *components = [calendar components: ( NSWeekCalendarUnit | NSWeekdayCalendarUnit | NSYearCalendarUnit) fromDate:currentDate];
int weekday = components.weekday;
if (weekday == 1) {
[components setWeek:components.week -1];
}else{
[components setWeekday:1];
}
currentDate = [calendar dateFromComponents:components];
【问题讨论】:
-
为什么将星期设置为
-1?如果你想上周获得,只需components.week -= 1; -
我正在使用 dateByAddingComponents 并将日期设置为 -1 得到最后一天,我认为添加时将星期设置为 -1 得到最后一周。
标签: ios objective-c nsdate nscalendar nsdatecomponents