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");
}
iOS: How to Get A Device's Current Time To Perform An Action? [duplicate]
-
26-06-2023 - |
Question
What's the best way to get the a user's current time (12:00pm etc) in order to perform an action? I have a game where I'd like to display night-time images if the current time for a user is between 8pm - 5am.
Solution
OTHER TIPS
NSDate *currentTime = [NSDate date];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"hh-mm"];
NSString *resultString = [dateFormatter stringFromDate: currentTime];
Straight way would be:
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];
I do like helperfunctions, so you could something like this, if you need this function more frequent and want to keep your code bit clean:
- (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];
}
Then call the function like this, where hour and minute could be common class variables:
NSInteger hour, minute;
NSDate *date = [NSDate date];
[self getHour:&hour andMinute:&minute fromDate:date];
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow