iOS:如何获取设备的当前时间来执行操作?

时间:2014-04-03 01:49:49

标签: ios objective-c ios7 nstimer

为了执行操作,获取用户当前时间(中午12:00等)的最佳方法是什么?我有一个游戏,如果用户当前的时间是晚上8点到早上5点,我想显示夜间图像。

3 个答案:

答案 0 :(得分:2)

NSDate *currentTime = [NSDate date];

NSDateFormatter *timeFormatter = [[NSDateFormatter alloc] init];
[timeFormatter setDateFormat:@"HH"];

NSString *hourCountString = [timeFormatter stringFromDate:currentTime];

int hourCountInt = [hourCountString intValue];

//time between 8PM - 5AM.
if(hourCountInt > 20 || hourCountInt < 5)
{
    NSLog(@"display night-time images");
}

答案 1 :(得分:0)

NSDate *currentTime = [NSDate date];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"hh-mm"];
NSString *resultString = [dateFormatter stringFromDate: currentTime];

答案 2 :(得分:0)

直道将是:

NSCalendar *calendar= [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSCalendarUnit unitFlags = NSHourCalendarUnit | NSMinuteCalendarUnit;
NSDate *date = [NSDate date];
NSDateComponents *dateComponents = [calendar components:unitFlags fromDate:date];

NSInteger hour = [dateComponents hour];
NSInteger minute = [dateComponents minute];

我喜欢helperfunctions,所以你可以这样,如果你需要更频繁的这个功能,并希望保持你的代码清洁:

- (void) getHour:(NSInteger *)hour andMinute:(NSInteger *)minute fromDate:(NSDate *)date
{
    NSCalendar *calendar= [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
    NSCalendarUnit unitFlags = NSHourCalendarUnit | NSMinuteCalendarUnit;
    NSDateComponents *dateComponents = [calendar components:unitFlags fromDate:date];

    *hour = [dateComponents hour];
    *minute = [dateComponents minute];
}

然后调用这样的函数,其中小时和分钟可以是常见的类变量:

NSInteger hour, minute;
NSDate *date = [NSDate date];
[self getHour:&hour andMinute:&minute fromDate:date];