2013-04-04 33 views
0

如果我说upcoming monday那么我怎样才能得到日期upcoming monday我怎样才能得到即将到来的一天的日期 - 目标C

一样,今天是Thu, 04-04-2013比我怎么能得到什么日期将在未来wednesday

希望我能够澄清你。

类似的问题在这里问,但我无法理解这一点:

Get the date of next saturday in Objective-C?

+1

应该我给的解决方案,或者你会搜索? – 2013-04-04 12:30:22

+0

请给解答。 – 2013-04-04 12:33:46

+1

不要告诉我们你无法理解你确切问题的答案。告诉我们你不明白答案的哪一部分。 – 2013-04-04 18:51:45

回答

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

我最喜欢你的答案。这很容易理解。但是如果今天是'Friday'而不是'next-friday',它会给'今天的日期'!试图纠正这一点。谢谢 – 2013-04-05 05:20:53

+1

只是用'if(moveDays <= 0)'代替'if(moveDays <0)' – 2013-04-05 05:25:00

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

我受到刺激...全身......本周末将拜访医生。由于许多人特别是“Viki”,他们说从来没有做60 * 60 * 24,因为所有的日子都没有60秒* 60分钟* 24小时,也有一些日光等。每当2-3个月回来,我用这个技巧,我得到批量降价。但你很热,每个人都喜欢你,所以upvote :) – 2013-04-05 05:27:36

+0

如果我想找到其他日子,我需要改变4,7,6或什么? – 2013-04-05 05:30:18

+0

我把这留给用户作为练习。找出算法是什么。 – 2013-04-05 11:03:22

相关问题