当前周开始和结束日期

当前周开始和结束日期

本文介绍了当前周开始和结束日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想获取当前周的开始和结束日期,我还想使用之前的
周开始和结束日期以及当月的开始和结束日期的下周。

I want to get the current week start and end date and I also want to use the previousweek start and end date and next week of the start and end date in current month.

感谢您的提前。

推荐答案

我解决问题感谢支持

代码: - 它给出当前的开始和结束日期。

Code :- it give the current week start and end 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);

这篇关于当前周开始和结束日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-13 06:47