我想知道什麼是NSDateFormatter
概念。我在我的應用程序中使用過它,但我對它的格式有點困惑。NSDateFormatter本週的最後一天
設置在我的模擬器:
settings->Language & Region United States,Calendar Gregorian calendar.
我已經使用這個代碼,日期轉換爲字符串:
NSDateFormatter*defaultFormatter = [[NSDateFormatter alloc] init]; [defaultFormatter setDateFormat:@"MM/dd/yyyy"];
要得到周的最後一天,我用這個代碼。這裏
date
是2015-03-31 18:30:00 +0000
:NSDate *today =date; //Week End Date NSCalendar *gregorianEnd = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar]; [gregorianEnd setFirstWeekday:1]; 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]; NSString* dateEndPrev = [defaultFormatter stringFromDate:EndOfWeek]; NSDate* weekEndPrev = [defaultFormatter dateFromString:dateEndPrev] ; NSLog(@"EndDate:%@",weekEndPrev); //prints ===>2015-04-04 18:30:00 +0000 return [defaultFormatter stringFromDate:weekEndPrev]; //==>04/05/2015
我不知道爲什麼它從給定的日期將在第二天。