问题
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