可可在一周内获得第一天 [英] Cocoa get first day in week
本文介绍了可可在一周内获得第一天的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何获得一周的第一天约会
How to get the first day of a week for a date
这似乎更容易,因为:
- 当星期一开始星期日时,我需要回到星期日日期
- 如果它在星期一开始,我需要得到星期一日期
输入日期是一周中的任何日期与时间...我尝试了几种方法,但边缘情况使它难以理解
the input date is any date in week with time... i tried several approaches, but the edge case make it difficould
我做了一个函数,然而它不能100%工作(不确定[components setDay:-weekday + 2];)
i made a function, which however doesn't work in 100% (not sure about the [components setDay: -weekday + 2];)
- (NSDate *)firstDateOfWeek {
NSCalendar * calendar = [NSCalendar currentCalendar];
NSDateComponents *weekdayComponents = [calendar components:(NSDayCalendarUnit | NSWeekdayCalendarUnit) fromDate:self];
// because sunday is 0, we need it to be 6
NSInteger weekday = (([weekdayComponents weekday] + 6) % 7);
NSDateComponents *components = [calendar components:(NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSWeekdayCalendarUnit) fromDate:self];
[components setDay: -weekday + 2];
return [calendar dateFromComponents:components];
}
推荐答案
这是更容易使用 rangeOfUnit
日历方法,该方法根据当前区域设置正确处理一周开始:
It is easier to use the rangeOfUnit
calendar method, which handles "start of the week" correctly according to the current locale:
NSDate *date = your date;
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDate *startOfWeek;
[calendar rangeOfUnit:NSWeekOfYearCalendarUnit
startDate:&startOfWeek
interval:NULL
forDate:date];
使用 NSDateComponents
,它将如下工作(假设一周有7天):
Using NSDateComponents
, it would work as follows (assuming that a week has 7 days):
NSDate *date = your date;
NSDateComponents *comp = [calendar components:NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit|NSWeekdayCalendarUnit
fromDate:date];
NSDate *startOfDay = [calendar dateFromComponents:comp];
NSInteger diff = (NSInteger)[calendar firstWeekday] - (NSInteger)[comp weekday];
if (diff > 0)
diff -= 7;
NSDateComponents *subtract = [[NSDateComponents alloc] init];
[subtract setDay:diff];
NSDate *startOfWeek = [calendar dateByAddingComponents:subtract toDate:startOfDay options:0];
这篇关于可可在一周内获得第一天的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文