在我的应用程序中,我使用以下代码来检索当前日期和日期: -
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);
但是使用上面的代码我只得到当天和日期和一周的第一天,但我需要得到一周的最后一天。但它给出了错误的输出。我的代码在哪里错了,需要进行哪些修改才能获得最后一天/哪一周?
答案 0 :(得分:0)
当您致电setDay时:您有时会将其设置为负数日。我不知道setDay和/或dateFromComponents:是否会处理它。
要为过去(或将来)的日期/时间创建NSDate,您可以减去(或添加)您想要返回(或转发)的秒数,如下所示:
// 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];