簡體   English   中英

顯示當前星期的開始和結束日期

[英]disply the current week start and end date

我想在UINavigationBar顯示當前周,然后單擊“下一個”或“上一個”按鈕以顯示“上一周”或“下周”

例:

July 22 - July 28
July 29 - Auguest 4

要獲得一周的第一個日期,您可以執行以下操作:

- (NSDate *)firstDayOfWeekFromDate:(NSDate *)date {
    CFCalendarRef currentCalendar = CFCalendarCopyCurrent();
    NSDateComponents *components = [CURRENT_CALENDAR components:DATE_COMPONENTS  fromDate:date];
    [components setDay:([components day] - ([components weekday] - CFCalendarGetFirstWeekday(currentCalendar)))];
    //[components setDay:(CFCalendarGetFirstWeekday(currentCalendar))];
    [components setHour:0];
    [components setMinute:0];
    [components setSecond:0];
    CFRelease(currentCalendar);
    return [CURRENT_CALENDAR dateFromComponents:components];
}

在一天的第一周之后,您可以按照@vikas的上述答案中的建議計算天數:)

 NSDate * selectedDate = [NSDate date];


-(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]];

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM