2014-06-20 83 views
2

我們如何才能獲得當天星期幾(星期一至星期日)的特定日期?例如我想了解這個星期日的日期或上週一的日期。如何從本週的星期幾名稱中獲得具體日期

編輯:在這裏,我如何與的@juniperi的鏈接

//To get current day 
CFAbsoluteTime at = CFAbsoluteTimeGetCurrent(); 
CFTimeZoneRef tz = CFTimeZoneCopySystem(); 
SInt32 currentWeekdayNumber = CFAbsoluteTimeGetDayOfWeek(at, tz); 

//We are adding or substracting from the day we want and add to the current date 
NSDate *now = [NSDate date]; 
int daysToAdd = theDayNumberWeWant - currentWeekdayNumber; 
NSDate *newDate1 = [now dateByAddingTimeInterval:60*60*24*daysToAdd]; 
+1

http://stackoverflow.com/questions/4269093/how-do-i-get-the-day-of-the-week-in-objective-c?rq=1 – juniperi

+0

感謝,這是有益的。 – birdcage

回答

2
int yourDOW = [[[NSCalendar currentCalendar] components:NSWeekdayCalendarUnit 
    fromDate:yourDate] weekday]; 

這你可以得到這一天是有當前日期的方式幫助解決的問題,如:星期一,週二,等

根據這一點,你可以計算出下一個/上一天和/或日期,既:

例如:

(星期日用1表示)2014年6月20日是星期五,那麼結果是 6.然後它意味着上個星期一是:date - (currentDay - requiredDay)= 20 - (6(星期五) - 2(星期一) )= 20 - (4)= 16

這意味着,2014年6月16日是最後一個星期一。

希望這會有所幫助。有關更多詳細信息,請參閱NSDateComponents.

+0

感謝您的幫助。我以非常相似的方式解決。你的帖子很有幫助。檢查我的第一篇文章。 – birdcage

1

傳遞您的日期此方法將返回此日期存在的一週中的第一天的日期。就像你通過當前日期一樣,你會得到本週第一天的日期。像這樣你可以計算其他日子的日期。

+ (NSDate *) getFirstDayOfTheWeekFromDate:(NSDate*)givenDate 
{ 
NSCalendar *calendar = [NSCalendar currentCalendar]; 

NSDateComponents *components = [calendar components:NSYearCalendarUnit|NSMonthCalendarUnit|NSWeekCalendarUnit|NSWeekdayCalendarUnit fromDate:givenDate]; 
[components setWeekday:1]; 
[components setWeek:[components week]]; 

return [calendar dateFromComponents:components]; 
} 
相關問題