How can i get date of a coming day - Objective C [duplicate]

生来就可爱ヽ(ⅴ<●) 提交于 2019-12-13 03:03:53

问题


If I say upcoming monday then how can I get date of upcoming monday?

Like, today is Thu, 04-04-2013 than how can I get what date will be on coming wednesday?

Hope I am able to clarify you.

Similar question was asked here but I'm not able to understand this:

Get the date of next saturday in Objective-C?


回答1:


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);



回答2:


Just to irritate 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);


来源:https://stackoverflow.com/questions/15811007/how-can-i-get-date-of-a-coming-day-objective-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!