本周开始和结束date

我想获得当前的一周的开始和结束date,我也想使用当前月份的开始和结束date以及下周的开始和结束date。

提前致谢。

rangeOfUnit:startDate:interval:forDate: 它给你一定的时间单位的开始和间隔。 有了它,很容易find使用的日历中的一周的开始,并添加范围1以获得该周的最后一秒。

 NSCalendar *cal = [NSCalendar currentCalendar]; NSDate *now = [NSDate date]; NSDate *startOfTheWeek; NSDate *endOfWeek; NSTimeInterval interval; [cal rangeOfUnit:NSWeekCalendarUnit startDate:&startOfTheWeek interval:&interval forDate:now]; //startOfWeek holds now the first day of the week, according to locale (monday vs. sunday) endOfWeek = [startOfTheWeek dateByAddingTimeInterval:interval-1]; // holds 23:59:59 of last day in week. 

我解决这个问题感谢支持

代码: – 它给当前的周开始和结束date。

  NSDate *today = [NSDate date]; NSLog(@"Today date is %@",today); dateFormat = [[NSDateFormatter alloc] init]; [dateFormat setDateFormat:@"yyyy-MM-dd"];// you can use your format. //Week Start Date NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar]; NSDateComponents *components = [gregorian components:NSWeekdayCalendarUnit | NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit fromDate:today]; int dayofweek = [[[NSCalendar currentCalendar] components:NSWeekdayCalendarUnit fromDate:today] weekday];// this will give you current day of week [components setDay:([components day] - ((dayofweek) - 2))];// for beginning of the week. NSDate *beginningOfWeek = [gregorian dateFromComponents:components]; NSDateFormatter *dateFormat_first = [[NSDateFormatter alloc] init]; [dateFormat_first setDateFormat:@"yyyy-MM-dd"]; dateString2Prev = [dateFormat stringFromDate:beginningOfWeek]; weekstartPrev = [[dateFormat_first dateFromString:dateString2Prev] retain]; NSLog(@"%@",weekstartPrev); //Week End Date NSCalendar *gregorianEnd = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar]; NSDateComponents *componentsEnd = [gregorianEnd components:NSWeekdayCalendarUnit | NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit fromDate:today]; int Enddayofweek = [[[NSCalendar currentCalendar] components:NSWeekdayCalendarUnit fromDate:today] weekday];// this will give you current day of week [componentsEnd setDay:([componentsEnd day]+(7-Enddayofweek)+1)];// for end day of the week NSDate *EndOfWeek = [gregorianEnd dateFromComponents:componentsEnd]; NSDateFormatter *dateFormat_End = [[NSDateFormatter alloc] init]; [dateFormat_End setDateFormat:@"yyyy-MM-dd"]; dateEndPrev = [dateFormat stringFromDate:EndOfWeek]; weekEndPrev = [[dateFormat_End dateFromString:dateEndPrev] retain]; NSLog(@"%@",weekEndPrev); 

一个Swift版本

vikingosegundo的回答 :

 let calendar = NSCalendar.currentCalendar() var startOfTheWeek: NSDate? var endOfWeek: NSDate! var interval = NSTimeInterval(0) calendar.rangeOfUnit(.WeekOfMonth, startDate: &startOfTheWeek, interval: &interval, forDate: NSDate()) endOfWeek = startOfTheWeek!.dateByAddingTimeInterval(interval - 1) 

Swift 3(Xcode 8+)的优雅之处在于:

 extension Date { var startOfWeek: Date { let date = Calendar.current.date(from: Calendar.current.dateComponents([.yearForWeekOfYear, .weekOfYear], from: self))! let dslTimeOffset = NSTimeZone.local.daylightSavingTimeOffset(for: date) return date.addingTimeInterval(dslTimeOffset) } var endOfWeek: Date { return Calendar.current.date(byAdding: .second, value: 604799, to: self.startOfWeek)! } } 

我们可以像这样使用这个扩展:

 print(Date().startOfWeek) print(Date().endOfWeek) 

首先find当前date…

 NSDate *today = [NSDate date]; NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar]; NSDateComponents *weekdayComponents = [gregorian components:NSWeekdayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit fromDate:today]; 

计算从今天开始减less的天数,以获得一周中的第一天。 在这种情况下,星期一的第一天是星期一。 首先用周日整数减去0,然后在setDay中加2。

周日= 1,周一= 2,周二= 3,周三= 4,周四= 5,周五= 6,周六= 7。

 NSDateComponents *componentsToSubtract = [[NSDateComponents alloc] init]; [componentsToSubtract setDay: (0 - [weekdayComponents weekday]) + 2]; [componentsToSubtract setHour: 0 - [weekdayComponents hour]]; [componentsToSubtract setMinute: 0 - [weekdayComponents minute]]; [componentsToSubtract setSecond: 0 - [weekdayComponents second]]; 

创build一周的第一天的date

 NSDate *beginningOfWeek = [gregorian dateByAddingComponents:componentsToSubtract toDate:today options:0]; 

通过在第一天的date加上6,我们可以得到最后一天,在我们的例子星期天。

 NSDateComponents *componentsToAdd = [gregorian components:NSDayCalendarUnit fromDate:beginningOfWeek]; [componentsToAdd setDay:6]; NSDate *endOfWeek = [gregorian dateByAddingComponents:componentsToAdd toDate:beginningOfWeek options:0]; 

为下一个和前…

 -(IBAction)Week_CalendarActionEvents:(id)sender{ NSCalendar *gregorian = [[[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar] autorelease]; NSDateComponents *offsetComponents = [[[NSDateComponents alloc] init] autorelease]; NSDate *nextDate; if(sender==Week_prevBarBtn) // Previous button events [offsetComponents setDay:-7]; else if(sender==Week_nextBarBtn) // next button events [offsetComponents setDay:7]; nextDate = [gregorian dateByAddingComponents:offsetComponents toDate:selectedDate options:0]; selectedDate = nextDate; [selectedDate retain]; NSDateComponents *components = [gregorian components:NSWeekCalendarUnit fromDate:selectedDate]; NSInteger week = [components week]; NSDateFormatter *formatter = [[NSDateFormatter alloc] init]; [formatter setDateFormat:@"MMMM YYYY"]; NSString *stringFromDate = [formatter stringFromDate:selectedDate]; [formatter release]; [Week_weekBarBtn setTitle:[NSString stringWithFormat:@"%@,Week %d",stringFromDate,week]]; } 

这里是Swift 3版本: –

 extension Date { var startOfWeek: Date? { let gregorian = Calendar(identifier: .gregorian) guard let sunday = gregorian.date(from: gregorian.dateComponents([.yearForWeekOfYear, .weekOfYear], from: self)) else { return nil } return gregorian.date(byAdding: .day, value: 1, to: sunday) } var endOfWeek: Date? { let gregorian = Calendar(identifier: .gregorian) guard let sunday = gregorian.date(from: gregorian.dateComponents([.yearForWeekOfYear, .weekOfYear], from: self)) else { return nil } return gregorian.date(byAdding: .day, value: 7, to: sunday) } } 

你可以得到像这样的一周开始date和结束date:

 let startWeek = Date().startOfWeek let endWeek = Date().endOfWeek print(startWeek ?? "not found start date") print(endWeek ?? "not found end date") 

您可以通过以下代码获取当前date和date:

 NSDate *today = [NSDate date]; NSDateFormatter *dateFormat = [[[NSDateFormatter alloc] init] autorelease]; [dateFormat setDateFormat:@"EEEE"]; NSString *weekDay = [dateFormat stringFromDate:today]; [dateFormat setDateFormat:@"dd"]; NSString *thedate=[dateFormat stringFromDate:today]; //[dateFormat release]; NSLog(@"%@ %@", weekDay,thedate); 

现在,您需要在其中添加一些逻辑来计算一周的开始date和结束date。 逻辑会是这样的,

如果星期几是星期一

然后

开始date=当前date – 0

结束date=当前date+ 6

等等

我想你可以明白这一点。

这里有一些代码,它也检查一个星期的开始在前一个月的边缘情况。 您可以通过将setWeekday设置为7来获得周末,并且可以通过从[components week]减去1来获得前一周

 // Finds the date for the first day of the week - (NSDate *)getFirstDayOfTheWeekFromDate:(NSDate *)givenDate { NSCalendar *calendar = [NSCalendar currentCalendar]; // Edge case where beginning of week starts in the prior month NSDateComponents *edgeCase = [[NSDateComponents alloc] init]; [edgeCase setMonth:2]; [edgeCase setDay:1]; [edgeCase setYear:2013]; NSDate *edgeCaseDate = [calendar dateFromComponents:edgeCase]; NSDateComponents *components = [calendar components:NSYearCalendarUnit|NSMonthCalendarUnit|NSWeekCalendarUnit|NSWeekdayCalendarUnit fromDate:edgeCaseDate]; [components setWeekday:1]; // 1 == Sunday, 7 == Saturday [components setWeek:[components week]]; NSLog(@"Edge case date is %@ and beginning of that week is %@", edgeCaseDate , [calendar dateFromComponents:components]); // Find Sunday for the given date components = [calendar components:NSYearCalendarUnit|NSMonthCalendarUnit|NSWeekCalendarUnit|NSWeekdayCalendarUnit fromDate:givenDate]; [components setWeekday:1]; // 1 == Sunday, 7 == Saturday [components setWeek:[components week]]; NSLog(@"Original date is %@ and beginning of week is %@", givenDate , [calendar dateFromComponents:components]); return [calendar dateFromComponents:components]; } 
 //Begining of Week Date - (NSDate*) beginingOfWeekOfDate{ NSCalendar *tmpCalendar = [NSCalendar currentCalendar]; NSDateComponents *components = [tmpCalendar components:NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitWeekOfYear|NSCalendarUnitWeekday fromDate:self];//get the required calendar units NSInteger weekday = tmpCalendar.firstWeekday; components.weekday = weekday; //weekday components.hour = 0; components.minute = 0; components.second = 0; NSDate *fireDate = [tmpCalendar dateFromComponents:components]; return fireDate; } //End of Week Date -(NSDate *)endOfWeekFromDate{ NSCalendar *tmpCalendar = [NSCalendar currentCalendar]; NSDateComponents *components = [tmpCalendar components:NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitWeekOfYear|NSCalendarUnitWeekday fromDate:self];//get the required calendar units int weekday = 7; //Saturday if (tmpCalendar.firstWeekday != 1) { weekday = 1; } components.weekday = weekday;//weekday components.hour = 23; components.minute = 59; components.second = 59; NSDate *fireDate = [tmpCalendar dateFromComponents:components]; return fireDate; } 

通过利用NSDate的方法rangeOfUnit:startDate:interval:forDate:有一个更简单的方法来实现这一点:

 - (void)startDate:(NSDate **)start andEndDate:(NSDate **)end ofWeekOn:(NSDate *)date{ NSDate *startDate = nil; NSTimeInterval duration = 0; BOOL b = [[NSCalendar currentCalendar] rangeOfUnit:NSWeekCalendarUnit startDate:&startDate interval:&duration forDate:date]; if(! b){ *start = nil; *end = nil; return; } NSDate *endDate = [startDate dateByAddingTimeInterval:duration-1]; *start = startDate; *end = endDate; } NSDate *this_start = nil, *this_end = nil; [self startDate:&this_start andEndDate:&this_end ofWeekOn:[NSDate date]]; 

所以现在你有本周的开始date和结束date。 然后上周:

 NSDate *lastWeekDate = [this_start dateByAddingTimeInterval:-10]; NSDate *last_start = nil, *last_end = nil; [self startDate:&last_start andEndDate:&last_end ofWeekOn:lastWeekDate]; 

下周:

 NSDate *nextWeekDate = [this_end dateByAddingTimeInterval:10]; NSDate *next_start = nil, *next_end = nil; [self startDate:&next_start andEndDate:&next_end ofWeekOn:nextWeekDate]; 

现在你拥有了全部。

Swift 3

首先find当前date…

  let today = Date() let gregorian = Calendar(identifier: .gregorian) var weekdayComponents: DateComponents? = gregorian.dateComponents([.weekday], from: today) 

星期一= 1,星期一= 2,星期二= 3,星期三= 4,星期四= 5,星期五= 6,星期六= 7。

  var componentsToSubtract = DateComponents() componentsToSubtract.day = (0 - (weekdayComponents?.weekday!)!) + 2 beginningOfWeek = gregorian.date(byAdding: componentsToSubtract, to: today) var componentsToAdd: DateComponents? = gregorian.dateComponents([.day], from: beginningOfWeek!) componentsToAdd?.day = 6 endOfWeek = gregorian.date(byAdding: componentsToAdd!, to: beginningOfWeek!) let components: DateComponents? = gregorian.dateComponents([.month], from: beginningOfWeek!) let month: Int? = components?.month let components1: DateComponents? = gregorian.dateComponents([.month], from: endOfWeek!) let month1: Int? = components1?.month print("\(month) - \(month1)") showDate(start:beginningOfWeek!, end:endOfWeek!, strtMn:month!, endMn:month1!) func showDate(start:Date, end:Date, strtMn:Int, endMn:Int) { if strtMn == endMn{ let formatter = DateFormatter() formatter.dateFormat = "MMM dd" let stringFromDate: String = formatter.string(from: start) let formatter1 = DateFormatter() formatter1.dateFormat = "dd" let stringFromDate1: String = formatter1.string(from: end) print("\(stringFromDate) - \(stringFromDate1)") lblDate.text = "\(stringFromDate) - \(stringFromDate1)" } else{ let formatter = DateFormatter() formatter.dateFormat = "MMM dd" let stringFromDate: String = formatter.string(from: start) let formatter1 = DateFormatter() formatter1.dateFormat = "MMM dd" let stringFromDate1: String = formatter1.string(from: end) print("\(stringFromDate) - \(stringFromDate1)") lblDate.text = "\(stringFromDate) - \(stringFromDate1)" } } 

为下一个和前…

 @IBAction func week_CalendarActionEvents(_ sender: UIButton) { let gregorian = Calendar(identifier: .gregorian) var offsetComponents = DateComponents() var nextStrtDate: Date? var nextEndDate: Date? var startDate: Date? var endDate: Date? startDate = beginningOfWeek endDate = endOfWeek if sender.tag == 1 { offsetComponents.day = -7 } else if sender.tag == 2 { offsetComponents.day = 7 } nextStrtDate = gregorian.date(byAdding: offsetComponents, to:startDate!) startDate = nextStrtDate beginningOfWeek = startDate nextEndDate = gregorian.date(byAdding: offsetComponents, to: endDate!) endDate = nextEndDate endOfWeek = endDate let components: DateComponents? = gregorian.dateComponents([.month], from: startDate!) let month: Int? = components?.month let components1: DateComponents? = gregorian.dateComponents([.month], from: endDate!) let month1: Int? = components1?.month print("\(month)- \(month1)") showDate(start:startDate!, end:endDate!, strtMn:month!, endMn:month1!) } 

在迅速3.0

 let cal = NSCalendar.current //weekday let weekday = cal.component(.weekday, from: Date()) var dateComp = cal.dateComponents([.hour, .minute, .second, .day, .month, .year], from: Date()) print(dateComp.day!) //Start Date of the week - Sunday dateComp.day = dateComp.day! - (weekday - 1)// start date of week print(cal.date(from: dateComp)!) //End Date of the Week - Saturday dateComp = cal.dateComponents([.hour, .minute, .second, .day, .month, .year], from: Date()) dateComp.day = dateComp.day! + (7 - weekday) print(cal.date(from: dateComp)!)