简体   繁体   中英

How to get specific date from weekday name in this week

How can we get date of a specific day in current week with day name (Between monday and sunday)? eg I want to learn what is the date of this sunday or what was the date of last monday.

EDIT: Here how I solved the problem with the help of @juniperi 's link

//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];

This the way you can get which day is there for current date, for eg: Monday, Tuesday, etc.

According to that, you can calculate next/prev day and/or dates, both:

For example:

(Sunday is represented with 1.) 20 Jun 2014 is Friday then result is 6. Then it means last Monday is: date - (currentDay - requiredDay) = 20 - ( 6 (friday) - 2 (monday)) = 20 - (4) = 16

It means, 16 Jun 2014 is the last Monday.

Hope this helps. For more details, refer NSDateComponents.

Pass your date this method will return you date of first day in the week this date exists. like if you pass current date you will get date of first day in current week. Like this you can calculate date of other days.

+ (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];
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM