[英]How to get specific date from weekday name in this week
如何獲得帶有日期名稱的當前周中特定日期的日期(星期一至星期日之間)? 例如,我想了解這個星期幾或上個星期一的日期。
編輯:在這里我如何解決@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];
int yourDOW = [[[NSCalendar currentCalendar] components:NSWeekdayCalendarUnit
fromDate:yourDate] weekday];
這樣,您可以獲取當前日期的哪一天,例如:星期一,星期二等。
據此,您可以計算下一個/上一個日期和/或日期,兩者都可以:
例如:
(星期日用1表示。)2014年6月20日是星期五,結果是6。則表示上周一是:日期-(currentDay-requiredDay)= 20-(6(星期五)-2(星期一))= 20-( 4)= 16
也就是說,2014年6月16日是最后一個星期一。
希望這可以幫助。 有關更多詳細信息,請參見NSDateComponents。
傳遞您的日期,此方法將返回您存在該日期的第一天的日期。 就像您傳遞當前日期一樣,您將獲得當前星期第一天的日期。 這樣,您可以計算其他日期的日期。
+ (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];
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.