[英]Get Week Start date returning next week day if today is sunday
i have a function which returns weekdays by passing any specific day, in my app , monday will be the week start day , it works fine except when settings current day to sunday, in this case the function is returning next weekdays , 我有一个函数,可以通过传递任何特定的日期来返回工作日,在我的应用中, 星期一将是星期开始日 ,除非将当前日期设置为星期日,否则它可以正常工作,在这种情况下,该函数将在下一个工作日返回,
+(NSMutableArray*) getWeekDatesList :(NSDate*) date {
@autoreleasepool {
NSDate *startingDateOfWeek = [self getWeekStartDateWithDate:date];
return [self getWeekDatesListWithStartDate:startingDateOfWeek];
}
},
and function to get week start date is, 获取星期开始日期的功能是
+(NSDate*) getWeekStartDateWithDate:(NSDate*) date{
@autoreleasepool {
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
[gregorian setLocale:[NSLocale currentLocale]];
[gregorian setFirstWeekday:2]; // 2 monday
[gregorian setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"GMT"]];
NSDateComponents *components = [gregorian components:NSWeekdayCalendarUnit | NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSWeekOfYearCalendarUnit |NSWeekCalendarUnit fromDate:date];
int value =([components day]-([components weekday]-2));
[components setDay:value];
[components setHour:0];
[components setMinute:0];
[components setSecond:0];
NSDate *beginningOfWeek = [gregorian dateFromComponents:components];
return beginningOfWeek;
}
}
Example: 例:
settings today as Sunday April 20 2014 , am getting week start date as April 21 2014 , but expected week start date is April 13 2014 今天的设置为2014年4月20日 ( 星期日) ,周开始日期为2014年4月21日 ,但预计周开始日期为2014年4月13日
how can i make it work correctly even when current day is set to sunday ? 即使将当前日期设置为星期日,我如何使它正常工作?
Thanks 谢谢
In your calculation you would have to check if [components weekday]
is less or greater than 2 (Monday) and modify the components accordingly to get the previous Monday. 在计算中,您必须检查[components weekday]
是否小于或大于2(Monday),并相应地修改这些组件以获得上一个星期一。
But you can simplify the calculation to: 但是您可以将计算简化为:
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
// [gregorian setLocale:[NSLocale currentLocale]]; (This is the default.)
[gregorian setFirstWeekday:2]; // 2 = Monday
[gregorian setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"GMT"]];
NSDate *beginningOfWeek;
[gregorian rangeOfUnit:NSWeekCalendarUnit startDate:&beginningOfWeek interval:NULL forDate:date];
This gives 2014-04-14 00:00:00 +0000 (a Monday) as expected. 这将按预期提供2014-04-14 00:00:00 +0000 (星期一)。
Remark: You should check if you really want to set the time zone to GMT. 备注:您应检查是否确实要将时区设置为GMT。 If you don't set a time zone then you will get the beginning of the week according to your local time zone. 如果您未设置时区,那么您将根据当地时区进入一周的开始时间。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.