我怎样才能得到即将到来的日期 - 目标C.

时间:2013-04-04 12:22:50

标签: objective-c nsdate nsdateformatter ios6.1

如果我说upcoming monday那么我如何才能获得upcoming monday的日期?

就像,今天是Thu, 04-04-2013,我怎么能得到即将到来的wednesday日期?

希望我能够澄清你。

这里问了类似的问题,但我无法理解:

Get the date of next saturday in Objective-C?

2 个答案:

答案 0 :(得分:6)

NSCalendar *gregorian = [[NSCalendar alloc]initWithCalendarIdentifier:NSGregorianCalendar];
NSDate *date = [NSDate date];
NSDateComponents *weekdayComponents = [gregorian components:NSWeekdayCalendarUnit fromDate:date];
NSInteger todayWeekday = [weekdayComponents weekday];

enum Weeks {
    SUNDAY = 1,
    MONDAY,
    TUESDAY,
    WEDNESDAY,
    THURSDAY,
    FRIDAY,
    SATURDAY
};

NSInteger moveDays=WEDNESDAY-todayWeekday;
if (moveDays<=0) {
    moveDays+=7;
}

NSDateComponents *components = [NSDateComponents new];
components.day=moveDays;

NSCalendar *calendar=[[NSCalendar alloc] initWithCalendarIdentifier: NSGregorianCalendar];
NSDate* newDate = [calendar dateByAddingComponents:components toDate:date options:0];

NSLog(@"%@",newDate);

答案 1 :(得分:1)

只是为了激怒Anoop;):

NSDate* now = [NSDate date];
NSTimeInterval nowInterval = [now timeIntervalSince1970];
int days = (int)(nowInterval / (24 * 60 * 60));
int today = (days + 4) % 7;
NSDate* saturday = [NSDate dateWithTimeIntervalSince1970:nowInterval + (6 - today) * 24 * 60 * 60];
NSLog(@"saturday = %@", saturday);