dot*_*dot 3 iphone cocoa-touch nsdate
我想倒计时到下一个小时.倒计时到特定时间非常容易,例如:
NSDate *midnight = [NSDate dateWithNaturalLanguageString:@"midnight tomorrow"];
Run Code Online (Sandbox Code Playgroud)
如何为"每小时的开始"定义NSDate?
谢谢!
编辑:这是我目前的.无法将解决方案集成到我的代码中.任何帮助将不胜感激.:)
-(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];
}
Run Code Online (Sandbox Code Playgroud)
Vla*_*mir 16
正如+dateWithNaturalLanguageStringMacOS SDK上提供的那样,您的目标是iPhone,您需要制作自己的方法.我认为NSCalendar上课可以帮助你:
- (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];
}
Run Code Online (Sandbox Code Playgroud)
我没有检查过这段代码,但它(至少这种方法)必须有效.
最简单的方法可能是操纵时间戳,将其四舍五入到当前小时的开头并添加1小时
- (NSDate*)nextHourDateForDate:(NSDate*)date {
NSTimeInterval timestamp = [date timeIntervalSince1970];
NSTimeInterval current = timestamp - fmod(timestamp, 3600);
NSTimeInterval next = current + 3600;
return [NSDate dateWithTimeIntervalSince1970:next];
}
Run Code Online (Sandbox Code Playgroud)
使用 DateComponents 和 Date,您可以通过向给定日期添加负数的分钟和一小时来获得它。
Swift3(作为扩展):
extension Date {
public var nextHour: Date {
let calendar = Calendar.current
let minutes = calendar.component(.minute, from: self)
let components = DateComponents(hour: 1, minute: -minutes)
return calendar.date(byAdding: components, to: self) ?? self
}
}
Run Code Online (Sandbox Code Playgroud)
使用它 let nextHourDate = myDate.nextHour
请参阅 Apple日期和时间编程指南以供参考。
================================================== ==========================
ObjectiveC(作为静态方法):
+ (NSDate *)nextHourDate:(NSDate *)date{
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *components = [calendar components:NSMinuteCalendarUnit|NSHourCalendarUnit fromDate:date];
components.minute = -components.minute;
components.hour = 1;
return [calendar dateByAddingComponents:components toDate:date options:0];
}
Run Code Online (Sandbox Code Playgroud)
并调用它:
[YourClass nextHourDate:yourDate];
Run Code Online (Sandbox Code Playgroud)