NSDate对于“下一个小时的开始” [英] NSDate for "beginning of next hour"

查看:132
本文介绍了NSDate对于“下一个小时的开始”的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想对下一个整小时进行倒计时。很容易倒计时到特定时间,例如:

I'd like to make a countdown to the next full hour. It's pretty easy to countdown to a specific time, like:

NSDate *midnight = [NSDate dateWithNaturalLanguageString:@"midnight tomorrow"]; 

如何为每小时开始定义NSDate?

how do I define an NSDate for "the beginning of every hour"?

谢谢!

编辑:这是我目前的。无法将解决方案集成到我的代码中。任何帮助将非常感谢。 :)

This is what I have currently. Having trouble integrating the solutions in to my code. Any help would be greatly appreciated. :)

-(void)updateLabel {
NSDate *now = [NSDate date];

NSDate *midnight = [NSDate dateWithNaturalLanguageString:@"midnight tomorrow"]; 

//num of seconds between mid and now
NSTimeInterval timeInt = [midnight timeIntervalSinceDate:now];
int hour = (int) timeInt/3600;
int min = ((int) timeInt % 3600) / 60;
int sec = (int) timeInt % 60;
countdownLabel.text = [NSString stringWithFormat:@"%02d:%02d:%02d", hour, min,sec];
}  


推荐答案

As + dateWithNaturalLanguageString 仅适用于MacOS SDK,而您的目标iPhone则需要自己制作一个方法。我认为 NSCalendar 类可以帮助您:

As +dateWithNaturalLanguageString is available on MacOS SDK only and your're targeting iPhone you'll need to make a method of your own. I think NSCalendar class can help you:

- (NSDate*) nextHourDate:(NSDate*)inDate{
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSDateComponents *comps = [calendar components: NSEraCalendarUnit|NSYearCalendarUnit| NSMonthCalendarUnit|NSDayCalendarUnit|NSHourCalendarUnit fromDate: inDate];
    [comps setHour: [comps hour]+1]; // Here you may also need to check if it's the last hour of the day
    return [calendar dateFromComponents:comps];
}

我没有检查过这个代码, 。

I have not checked this code but it (at least this approach) must work.

这篇关于NSDate对于“下一个小时的开始”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆