程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> 更多編程語言 >> 編程綜合問答 >> nsdate-ios-獲取一星期的始末日期

nsdate-ios-獲取一星期的始末日期

編輯:編程綜合問答
ios-獲取一星期的始末日期

代碼:

NSCalendar *calendar = [NSCalendar currentCalendar];
NSInteger weekNumber =  [[calendar components: NSWeekCalendarUnit fromDate:date] week];

應該如何獲取這個星期的始末日期(周一到周日)?
還有能不能獲取同一星期內所有的日期數組?

最佳回答:


獲取日期:

 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(@"StartDate:%@",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(@"EndDate:%@",weekEndPrev);
  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved