Harshit Goel Harshit Goel - 2 months ago 15
iOS Question

Change Background image once at 6 AM and other at 6 PM

I have two images one for morning which I need to display it after 6am and other for night which I need to display it at background after 6pm. Please help me in changing the display automatically at 6am-6pm and 6pm-6am .

NSDate *_currentDate = [NSDate date];
NSDateFormatter *_dateFormatter = [[NSDateFormatter alloc] init];
[_dateFormatter setDateFormat:@"yyyy-MM-dd' 06:00AM +0000'"]; // set the morning date here
NSString *_morningDateString = [_dateFormatter stringFromDate:_currentDate];
[_dateFormatter setDateFormat:@"yyyy-MM-dd' 06:00PM +0000'"]; // set the evening date here
NSString *_eveningDateString = [_dateFormatter stringFromDate:_currentDate];

[_dateFormatter setDateFormat:@"yyyy-MM-dd hh:mma zzz"];
NSDate *_morningDate = [_dateFormatter dateFromString:_morningDateString];
NSDate *_eveningDate = [_dateFormatter dateFromString:_eveningDateString];

NSTimeInterval _intervalToMorningDate = [_morningDate timeIntervalSinceDate:_currentDate];
NSTimeInterval _intervalToEveningDate = [_eveningDate timeIntervalSinceDate:_currentDate];

if (_intervalToMorningDate > 0) {
// now it is night
self.bgImage.image = [UIImage imageNamed:@"main_bg.png"];
[self performSelector:@selector(replaceTheBackgoundForMorning) withObject:nil afterDelay:_intervalToMorningDate];
} else {
// now it is daytime
self.bgImage.image = [UIImage imageNamed:@"daylight.png"];
[self performSelector:@selector(replaceTheBackgoundForEvening) withObject:nil afterDelay:_intervalToEveningDate];
}
-(void)replaceTheBackgoundForMorning {
// reaplce the backgound here
self.bgImage.image = [UIImage imageNamed:@"daylight.png"];
}

- (void)replaceTheBackgoundForEvening {
// reaplce the backgoung here
self.bgImage.image = [UIImage imageNamed:@"main_bg.png"];
}

Answer

Try to use NSDateComponents like below

NSDateComponents *components = [[NSCalendar currentCalendar] components:NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit fromDate:[NSDate date]];
NSInteger nowHour = [components hour];
NSInteger nowMinute = [components minute];
NSInteger nowSecond = [components second];

if (nowHour < 6 || (nowHour > 18 || (nowHour == 18 && (nowMinute > 0 || nowSecond > 0)))) {
   // Time is 6pm to 6am
}
else{
    // Time is 6am to 6pm