user5842052
user5842052

Reputation:

How to get current seconds left to complete hour?

I want to get how many seconds are remaining to complete an hour. No matter which what time it is?

if its 05:01:00 then it should give 3540 seconds and if its 11:58:40 then it gives 80 seconds and so on. I try to find it on google but could not able to find it. Thanks in advance.

Upvotes: 0

Views: 197

Answers (3)

stevenpcurtis
stevenpcurtis

Reputation: 2001

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

Fill in with the correct times and dates to get the difference in seconds

Edit: An alternative method is to work out the currenthour and return as an integer. Then add one to the NSInteger returned as below (you will have to make sure to handle the case where it is after midnight though!)

NSDateComponents *components = [[NSCalendar currentCalendar] components:NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit fromDate:[NSDate date]];
NSInteger currentHour = [components hour];

Upvotes: -2

Duncan C
Duncan C

Reputation: 131418

@Vadian's answer is very good. (voted)

It requires iOS 8 or later however.

There are other ways you could do this using NSCalendar and NSDateComponents that would work with older OS versions.

You could use componentsFromDate to get the month, day, year, and hour from the current date, then increment the hour value and use the NSCalendar method dateFromComponents: to convert your to adjusted components back to a date.

Upvotes: 0

vadian
vadian

Reputation: 285079

NSCalendar has got methods to do that kind of date math:

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);

Upvotes: 4

Related Questions