简体   繁体   中英

How to find last day of week in iPhone?

In my application I'm using following codes to retrieve current date and day :-

NSDate *today1 = [NSDate date]; NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init]; [dateFormat setDateFormat:@"dd/MM/yyyy :EEEE"]; NSString *dateString11 = [dateFormat stringFromDate:today1];
NSLog(@"date: %@", dateString11);
//[dateFormat release];
NSCalendar *gregorian11 = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];  
NSDateComponents *components1 = [gregorian11 components:NSWeekdayCalendarUnit | NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit fromDate:today1];
[components1 setDay:([components1 day]-([components1 weekday]-1))];

NSDate *beginningOfWeek1 = [gregorian11 dateFromComponents:components1];
NSDateFormatter *dateFormat_first = [[NSDateFormatter alloc] init];
[dateFormat_first setDateFormat:@"dd/MM/yyyy :EEEE"];
NSString *dateString_first = [dateFormat_first stringFromDate:beginningOfWeek1];

NSLog(@"First_date: %@", dateString_first);
[components1 setDay:([components1 day]-([components1 weekday]-1) + 6)]; now =[gregorian dateFromComponents:components1]; [format setDateFormat:@"dd/MM/yyyy :EEEE"]; dateString = [format stringFromDate:now]; NSLog(@" week Last_date: %@", dateString);

but using above code I only got the current day and Date and first day of week but I need to get last day of week. But it gives the wrong output. Where am I wrong in my code and what modification is needed to get last day/date of week?

When you call setDay: you are sometimes setting it to a negative day. I don't know if setDay and/or dateFromComponents: will handle that.

To create a NSDate for a date/time that is in the past (or future) you can subtract (or add) the number of seconds that you want to go back (or forward), like this:

// convert to seconds
NSTimeInterval tmpSecs = [[NSDate date] timeIntervalSinceReferenceDate];
// Shift the date/time (in seconds) to a new date X days away:
tmpSecs += daysOffset * 86400;  // 86400 seconds per day
// convert back to NSDate and return the result
return [NSDate dateWithTimeIntervalSinceReferenceDate:tmpSecs];

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