Reputation: 45
I'm making an iOS application for iPhone, and I want to have two labels that is hidden on a specific time and shown on a specific time. Like Label1 is shown between 6am and 6pm and Label2 is shown between 6pm and 6am Any ideas?
Upvotes: 0
Views: 1336
Reputation: 737
NSDate *today = [NSDate date];
NSCalendar *gregorian = [[[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar] autorelease];
NSDateComponents *components = [gregorian components:(NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit) fromDate:today];
NSInteger hour = [components hour];
NSInteger minute = [components minute];
NSInteger second = [components second];
Now you have the hour, just add your normal logic. if want to be change the formate do this...
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"hh:mm a"];
// another is [formatter setDateFormat:@"hh:mm:ss"];
NSLog(@"Current Date: %@", [formatter stringFromDate:today]);
Upvotes: 1
Reputation: 20021
[NSDate date];
gives you the current date .Use date fromatter to get the fromat you need and use setText:
method to set the text.Fire it in a timer and set the text
NSDateFormatter *dateFormatter=[[NSDateFormatter alloc]init];
[dateFormatter setDateFormat:@"EEEE MMMM d, YYYY"];
NSLog(@"%@",[dateFormatter stringFromDate:[NSDate date]]);
[yourLabel setText:[dateFormatter stringFromDate:[NSDate date]]];
EDIT
full code,Try this
-(void)showtext
{
NSDateFormatter *dateFormatter=[[NSDateFormatter alloc]init];
[dateFormatter setDateFormat:@"hh:mm:ss"];
NSLog(@"%@",[dateFormatter stringFromDate:[NSDate date]]);
if( [self compareTimeIsbetween6])
{
[self.date1Label setHidden:NO];
[self.date2Label setHidden:YES];
[self.date1Label setText:[dateFormatter stringFromDate:[NSDate date]]];
}
else
{
[self.date1Label setHidden:YES];
[self.date2Label setHidden:NO];
[self.date2Label setText:[dateFormatter stringFromDate:[NSDate date]]];
}
}
-(BOOL)compareTimeIsbetween6
{
NSDateComponents *components = [[NSCalendar currentCalendar] components:NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit fromDate:[NSDate date]];
NSInteger currentHour = [components hour];
NSInteger currentMinute = [components minute];
NSInteger currentSecond = [components second];
if (currentHour < 6 || (currentHour > 18 || (currentHour == 18 && (currentMinute > 0 || currentSecond > 0)))) {
return YES;
}
else
{
return NO;
}
}
- (void)viewDidLoad
{
[super viewDidLoad];
[NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(showtext) userInfo:nil repeats:YES]; // Do any additional setup after loading the view, typically from a nib.
}
.h
@interface ViewController : UIViewController
@property (weak, nonatomic) IBOutlet UILabel *date1Label;
@property (weak, nonatomic) IBOutlet UILabel *date2Label;
Upvotes: 1