我想知道還有多少秒鐘才能完成一個小時。無論現在是幾點?如何獲得當前剩餘時間完成小時?
如果它05:01:00那麼它應該給3540秒 ,如果它的11:58:40那麼它會給出80秒等等。我試圖在谷歌上找到它,但無法找到它。 在此先感謝。
我想知道還有多少秒鐘才能完成一個小時。無論現在是幾點?如何獲得當前剩餘時間完成小時?
如果它05:01:00那麼它應該給3540秒 ,如果它的11:58:40那麼它會給出80秒等等。我試圖在谷歌上找到它,但無法找到它。 在此先感謝。
NSCalendar
得到了方法做那種日期數學(你必須確保處理它是午夜以後雖然如此!):
NSDate *now = [NSDate date];
NSCalendar *calendar = [NSCalendar currentCalendar];
// find next date where the minutes are zero
NSDate *nextHour = [calendar nextDateAfterDate:now matchingUnit:NSCalendarUnitMinute value:0 options:NSCalendarMatchNextTime];
// get the number of seconds between now and next hour
NSDateComponents *componentsToNextHour = [calendar components:NSCalendarUnitSecond fromDate:now toDate:nextHour options:0];
NSLog(@"%ld", componentsToNextHour.second);
非常感謝和高度讚賞 –
NSDate *date1 = [NSDate dateWithString:@"2010-01-01 00:00:00 +0000"];
NSDate *date2 = [NSDate dateWithString:@"2010-02-03 00:00:00 +0000"];
NSTimeInterval secondsBetween = [date2 timeIntervalSinceDate:date1];
中填寫正確的時間和日期,以獲得在幾秒鐘之差
編輯:另一種方法是制定出currentHour的,並返回一個整數。然後添加一個到NSInteger的返回如下
NSDateComponents *components = [[NSCalendar currentCalendar] components:NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit fromDate:[NSDate date]];
NSInteger currentHour = [components hour];
我不知道這兩個時間,我只知道當前的時間,我必須找出需要多少秒完成那個小時? –
http://developer.apple.com/documentation/Cocoa/Conceptual/DatesAndTimes/DatesAndTimes.html#//apple_ref/doc/uid/10000039 – stevenpcurtis
返回當前小時,然後計算當前小時+ 1-(NSInteger)currentHour { //實際上,這些調用可以結合使用 NSDate * now = [NSDate date]; NSCalendar * calendar = [NSCalendar currentCalendar]; NSDateComponents *組件= [日曆組件:NSHourCalendarUnit fromDate:now]; return [組件小時]; } – stevenpcurtis
@Vadian的回答非常好。 (投票)
但它需要iOS 8或更高版本。
還有其他方法可以使用NSCalendar
和NSDateComponents
這樣的方法來處理較舊的操作系統版本。
您可以使用componentsFromDate
從當前日期獲取月份,日期,年份和小時,然後遞增小時值並使用方法dateFromComponents:
將您的調整組件轉換回日期。
如果恰好在一小時的時間內打電話,您想要做什麼?返回當前小時或下一小時,這將在60分鐘後完成? –