2016-04-01 40 views
0

我的應用程序有一個聊天組件,用戶可以直接與客戶服務代表通話,如果他們在辦公時間請求幫助,我想確保通知用戶。將本地NSDate時間與PST時間的運行時間進行比較

辦公時間爲上午9點至晚上7點。

這是我現在的代碼,如果辦公室關閉,但它不能正常工作,則向用戶顯示通知。

- (void)checkOfficeHours { 

//set opening hours date 
NSDateComponents *openingTime = [[NSDateComponents alloc] init]; 
openingTime.hour = 9; 
openingTime.minute = 0; 

//set closing time hours 
NSDateComponents *closingTime = [[NSDateComponents alloc] init]; 
closingTime.hour = 19; 
closingTime.minute = 0; 

//get the pst time from local time 
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; 
[email protected]"hh:mm"; 
NSDate *currentDate = [NSDate date]; 
NSTimeZone *pstTimeZone = [NSTimeZone timeZoneWithAbbreviation:@"PST"]; 
dateFormatter.timeZone = pstTimeZone; 
NSString *pstTimeString = [dateFormatter stringFromDate:currentDate]; 

//convert pst date string back to date 
NSDate *now = [dateFormatter dateFromString:pstTimeString]; 

//create the current date component 
NSDateComponents *currentTime = [[NSCalendar currentCalendar] components:NSCalendarUnitHour|NSCalendarUnitMinute|NSCalendarUnitSecond fromDate:now]; 

//sort the array by times 
NSMutableArray *times = [@[openingTime, closingTime, currentTime] mutableCopy]; 
[times sortUsingComparator:^NSComparisonResult(NSDateComponents *t1, NSDateComponents *t2) { 
    if (t1.hour > t2.hour) { 
     return NSOrderedDescending; 
    } 

    if (t1.hour < t2.hour) { 
     return NSOrderedAscending; 
    } 
    // hour is the same 
    if (t1.minute > t2.minute) { 
     return NSOrderedDescending; 
    } 

    if (t1.minute < t2.minute) { 
     return NSOrderedAscending; 
    } 
    // hour and minute are the same 
    if (t1.second > t2.second) { 
     return NSOrderedDescending; 
    } 

    if (t1.second < t2.second) { 
     return NSOrderedAscending; 
    } 
    return NSOrderedSame; 

}]; 

//if the current time is in between (index == 1) then its during office hours 
if ([times indexOfObject:currentTime] == 1) { 
    NSLog(@"We are Open!"); 
    self.officeHoursView.hidden = YES; 
} else { 
    NSLog(@"Sorry, we are closed!"); 
    self.officeHoursView.hidden = NO; 
} 

}

回答

1

如果所有你關心的是它是否是當前上午9點和晚上7點之間的PST,你可以比很多更容易做到這一點。只需在PST中獲取當前時間的NSDateComponents,然後查看結果的hour屬性。

NSTimeZone *pst = [NSTimeZone timeZoneWithName:@"PST"]; 
NSDateComponents *pstComponentsForNow = [[NSCalendar currentCalendar] componentsInTimeZone:pst fromDate:[NSDate date]]; 

if ((pstComponentsForNow.hour >= 9) && (pstComponentsForNow.hour <= 19)) { 
    NSLog(@"Open"); 
} else { 
    NSLog(@"Closed"); 
} 

如果你還在乎一週或其他細節的一天,看看NSDateComponents其他屬性。

+0

謝謝!這似乎是做這個工作! –

相關問題