2012-05-10 100 views

回答

0

在這裏,我是位置代碼。看到它會幫助你。

NSDate *today = [NSDate date]; 
    NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init]; 
    [dateFormat setDateFormat:@"yyyy-MM-dd"];// you can use your format. 
    NSString *dateString = [dateFormat stringFromDate:today]; 


    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))];// for beginning of the week. 

    // or 

    [components setDay:([components day]+(7-dayofweek))];// for end day of the week 

    NSDate *beginningOfWeek = [gregorian dateFromComponents:components]; 
    NSDateFormatter *dateFormat_first = [[NSDateFormatter alloc] init]; 
    [dateFormat_first setDateFormat:@"yyyy-MM-dd"]; 
    NSString *dateString2 = [dateFormat stringFromDate:beginningOfWeek]; 

希望,這將幫助你......

+0

見我的編輯,讓你找到任何困難我知道。 ..享受... :) – Nit

+0

非常感謝你。 – user1268135

+0

如果它的幫助比你應該接受正確的答案。所以其他人(誰可能有同樣的問題)可以選擇正確的答案,這樣你可以幫助自己,stackover-flow,和其他人...享受.. :) – Nit

0

這將幫助你

NSCalendar *cal = [NSCalendar currentCalendar]; 
NSDateComponents *components = [cal components:(NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit) fromDate:[[NSDate alloc] init]]; 

[components setHour:-[components hour]]; 
[components setMinute:-[components minute]]; 
[components setSecond:-[components second]]; 
NSDate *today = [cal dateByAddingComponents:components toDate:[[NSDate alloc] init] options:0]; //This variable should now be pointing at a date object that is the start of today (midnight); 

[components setHour:-24]; 
[components setMinute:0]; 
[components setSecond:0]; 
NSDate *yesterday = [cal dateByAddingComponents:components toDate: today options:0]; 

components = [cal components:NSWeekdayCalendarUnit | NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit fromDate:[[NSDate alloc] init]]; 

[components setDay:([components day] - ([components weekday] - 1))]; 
NSDate *thisWeek = [cal dateFromComponents:components]; 

[components setDay:([components day] - 7)]; 
NSDate *lastWeek = [cal dateFromComponents:components]; 

[components setDay:([components day] - ([components day] -1))]; 
NSDate *thisMonth = [cal dateFromComponents:components]; 

[components setMonth:([components month] - 1)]; 
NSDate *lastMonth = [cal dateFromComponents:components]; 

NSLog(@"today=%@",today); 
NSLog(@"yesterday=%@",yesterday); 
NSLog(@"thisWeek=%@",thisWeek); 
NSLog(@"lastWeek=%@",lastWeek); 
NSLog(@"thisMonth=%@",thisMonth); 
NSLog(@"lastMonth=%@",lastMonth); 

Here

+0

非常感謝.. – user1268135

+0

如果您接受此代碼這個答案並增加你的觀點。 – akk

相關問題