获取星期日期在IOS SDK [英] Get weeks date in IOS SDK
问题描述
我想获得目前&下周有日期名称的日期。
I want to get the current & next week dates with day name.
如果今天的日期是28-06-2013(星期五),那么我想将日期从23-06-2013(星期日)至29-06-2013(星期六)作为本周的。
i.e. If today's date is 28-06-2013 (Friday) then I want to get the dates from 23-06-2013(sunday) to 29-06-2013 (Saturday) as the this current week.
下周
我想获得30-06-2013(星期日)至06-07-2013星期六)。
for next week I want to get dates from 30-06-2013(sunday) to 06-07-2013 (saturday).
我该如何做?
谢谢,
Here is sample code that does the trick.
- (NSArray *)daysThisWeek
{
return [self daysInWeek:0 fromDate:[NSDate date]];
}
- (NSArray *)daysNextWeek
{
return [self daysInWeek:1 fromDate:[NSDate date]];
}
- (NSArray *)daysInWeek:(int)weekOffset fromDate:(NSDate *)date
{
NSCalendar * calendar = [NSCalendar currentCalendar];
//请求当前周
NSDateComponents * comps = [[NSDateComponents alloc] init];
comps = [calendar components:NSWeekCalendarUnit | NSYearCalendarUnit fromDate:date];
//创建星期开始日期
NSDate * weekstart = [calendar dateFromComponents:comps];
if(weekOffset> 0){
NSDateComponents * moveWeeks = [[NSDateComponents alloc] init];
moveWeeks.week = 1;
weekstart = [calendar dateByAddingComponents:moveWeeks toDate:weekstart options:0];
}
//添加7天
NSMutableArray * week = [NSMutableArray arrayWithCapacity:7];
for(int i = 1; i <= 7; i ++){
NSDateComponents * compsToAdd = [[NSDateComponents alloc] init];
compsToAdd.day = i;
NSDate * nextDate = [calendar dateByAddingComponents:compsToAdd toDate:weekstart options:0];
[week addObject:nextDate];
}
return [NSArray arrayWithArray:week];
}
-(NSArray*)daysThisWeek
{
return [self daysInWeek:0 fromDate:[NSDate date]];
}
-(NSArray*)daysNextWeek
{
return [self daysInWeek:1 fromDate:[NSDate date]];
}
-(NSArray*)daysInWeek:(int)weekOffset fromDate:(NSDate*)date
{
NSCalendar *calendar = [NSCalendar currentCalendar];
//ask for current week
NSDateComponents *comps = [[NSDateComponents alloc] init];
comps=[calendar components:NSWeekCalendarUnit|NSYearCalendarUnit fromDate:date];
//create date on week start
NSDate* weekstart=[calendar dateFromComponents:comps];
if (weekOffset>0) {
NSDateComponents* moveWeeks=[[NSDateComponents alloc] init];
moveWeeks.week=1;
weekstart=[calendar dateByAddingComponents:moveWeeks toDate:weekstart options:0];
}
//add 7 days
NSMutableArray* week=[NSMutableArray arrayWithCapacity:7];
for (int i=1; i<=7; i++) {
NSDateComponents *compsToAdd = [[NSDateComponents alloc] init];
compsToAdd.day=i;
NSDate *nextDate = [calendar dateByAddingComponents:compsToAdd toDate:weekstart options:0];
[week addObject:nextDate];
}
return [NSArray arrayWithArray:week];
}
这篇关于获取星期日期在IOS SDK的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!