I need to display the exact local time and the time should be running.
Please help, if possible with sample code or explanation.
Thanks.
This returns the current date with Time
[NSDate date];
Now you can use NStimer to fetch the time every one second and display it.
NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:#selector(displayTime) userInfo:nil repeats:NO];
//Time Interval is one second
-(void) displayTime
{
NSDate *currentDate = [NSDate date];
NSDateFormatter *timeFormatter = [[[NSDateFormatter alloc]init]autorelease];
timeFormatter.dateFormat = #"HH:mm:ss a";
NSString *dateString = [timeFormatter stringFromDate: currentDate];
yourlabel.text = dateString;
[timeFormatter release]
}
Related
I know how to use NSDate to get the time and display it inside UILabel.
i need to display the date + hours and minutes.
any idea how can i keep it updated without busy-waiting?
Thanks!
Use NSTimer to update time on the label
- (void)viewDidLoad
{
[super viewDidLoad];
[NSTimer scheduledTimerWithTimeInterval:1 target:self selector:#selector(updateTime) userInfo:nil repeats:YES];
}
-(void)updateTime
{
NSDate *date= [NSDate date];
NSDateFormatter *formatter1 = [[NSDateFormatter alloc]init]; //for hour and minute
formatter1.dateFormat = #"hh:mm a";// use any format
clockLabel.text = [formatter1 stringFromDate:date];
[formatter1 release];
}
As your comments said , if you want when minutes changes you change the label.text
you should do like this :
1st: get the current time:
NSDate *date = [NSDate date];
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *dateComponents = [calendar components:NSHourCalendarUnit fromDate:date];
and set the label.text = CURRENTHOUR_AND_YOURMINNUTS;
and then refresh the label next minute,like this :
the first , you can check after 60 - nowSeconds
[self performSelector:#selector(refreshLabel) withObject:nil afterDelay:(60 - dateComponents.minute)];
- (void)refreshLabel
{
//refresh the label.text on the main thread
dispatch_async(dispatch_get_main_queue(),^{ label.text = CURRENT_HOUR_AND_MINUTES; });
// check every 60s
[self performSelector:#selector(refreshLabel) withObject:nil afterDelay:60];
}
It will check every minute , so the effecent is more than answers above.
When refreshLabel invocated , it means the minutes changed
You can use the NSTimer to periodically get the current time.
[NSTimer scheduledTimerWithTimeInterval:2 target:self selector:#selector(timerFired:) userInfo:nil repeats:YES];
- (void)timerFired:(NSTimer*)theTimer{
//you can update the UILabel here.
}
You can use NSTimer , but , given the above methods , the UILabel won't update on touch Events as the main thread will be busy tracking it.You need to add it to mainRunLOOP
NSTimer* timer = [NSTimer timerWithTimeInterval:1.0f target:self selector:#selector(updateLabelWithDate) userInfo:nil repeats:YES];
[[NSRunLoop mainRunLoop] addTimer:timer forMode:NSRunLoopCommonModes];
-(void)updateLabelWithDate
{
//Update your Label
}
You can change the time interval(rate at which you want Updation).
I've been searching internet for a few days till now. I did find some useful information but just want to make things perfect.
I'm trying to write a countdown app which only uses second, my current code is a bit too complex and maybe off the main road. Looking for someone who can straight it up.
- (void)updateTimer{
NSDate *currentDate = [NSDate date];
NSTimeInterval timeInterval = [currentDate timeIntervalSinceDate:startDate];
NSDate *timerDate = [NSDate dateWithTimeIntervalSince1970:timeInterval];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"s"];
[dateFormatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0.0]];
NSString *timeString=[dateFormatter stringFromDate:timerDate];
// where the part change time string back to int
NSString *changeToInt = timeString;
int stringInt = [changeToInt integerValue];
// loop for count down numbers
if ((buttValue - stringInt) > 0) {
leftTime = buttValue - stringInt;
[self updateValue];
} else {
leftTime = 0;
[self updateValue];
}
}
2 problems with the code, 1) do I have to go through all the date formatting to get a integer? 2) in the loop I used two variables, I was hoping to take one out and use something like --
I don't understand what you need exactly, but I think that you just want to get the number of seconds from now to a known date. The timeIntervalSinceNow method will give you a NSInteger value that represent the number of seconds from the receiver date until now, which, if the receiver is earlier than now, will be a negative value (otherwise it will be positive).
So, just to be more explicit:
- (void)updateTimer
{
leftTime = MAX(0, -[startDate timeIntervalSinceNow]); //if less than 0 will be forced to 0 -> date reached
[self updateValue];
}
As I said, I'm not sure this is what you want. If it's not, I am sorry.
Good luck!
-(void)initialiseTimer
{
[NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:#selector(timeElapsed) userInfo:nil repeats:YES];
startDate = [[NSDate date] retain];
}
-(void)timeElapsed
{
NSLog(#"Seconds elapsed since start date %d", abs([startDate timeIntervalSinceNow]));
}
you can manipulate it to make a count down style app.
Use this code !!
-(IBAction)startAndStop:(id)sender
{
startDate = [[NSDate date]retain];
if([btnStopWatch.titleLabel.text isEqualToString:#"Start"])
{
stopWatchTimer = [NSTimer scheduledTimerWithTimeInterval:1.0/100.0 target:self selector:#selector(updateTimer) userInfo:nil repeats:YES];
[btnStopWatch setTitle:#"Stop" forState:UIControlStateNormal];
}
else if([btnStopWatch.titleLabel.text isEqualToString:#"Stop"])
{
[stopWatchTimer invalidate];
[btnStopWatch setTitle:#"Start" forState:UIControlStateNormal];
}
}
- (void)updateTimer
{
NSDate *currentDate = [NSDate date];
NSTimeInterval timeInterval = [currentDate timeIntervalSinceDate:startDate];
NSDate *timerDate = [NSDate dateWithTimeIntervalSince1970:timeInterval];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"HH:mm:ss"];
[dateFormatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0.0]];
timeString=[dateFormatter stringFromDate:timerDate];
stopWatchLabel.text = timeString;
NSLog(#"Seconds elapsed since start date %d", abs([startDate timeIntervalSinceNow]));
}
I have an app that uses a stopwatch-style count up from 0 in HH:mm:ss format. The code looks pretty straightforward to me, and I can't think of a more efficient way to run it.
For some reason, when I run it, there is a very noticeable and consistent (every time I run it, in the same place) lag when the timer gets to 00:00:02. It stays on 00:00:02 for a full second, and then counts on normally. Why would this happen?
-(IBAction)startAndStop;
{
if (!timer) {
NSLog(#"Pressing Start Button");
[startAndStopButton setTitle:#"Stop" forState:0];
startDate = [[NSDate date] retain];
timerLabel.text = #"00:00:00";
timer = [NSTimer scheduledTimerWithTimeInterval:1
target:self
selector:#selector(timerStart)
userInfo:nil
repeats:YES];
} else {
NSLog(#"Pressing Stop Button");
[startAndStopButton setTitle:#"Start" forState:0];
[startDate release];
[timer invalidate];
timer = nil;
[timer release];
}
}
-(void)timerStart
{
NSDate *currentDate = [NSDate date];
NSTimeInterval countInSeconds = [currentDate timeIntervalSinceDate:startDate];
NSDate *timerDate = [NSDate dateWithTimeIntervalSinceReferenceDate:countInSeconds];
NSDateFormatter *df = [[NSDateFormatter alloc] init];
[df setDateFormat:#"HH:mm:ss"];
[df setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0.0]];
NSString *timeString = [df stringFromDate:timerDate];
[df release];
timerLabel.text = timeString;
}
NSTimer does not fire at exact times or time intervals (check the specification for the likely error). Thus it is possible for one late firing and one early firing to occur during the same clock second, when rounded to the nearest second, and you will see a stutter effect.
Instead, use a much faster timer (or CADisplaylink), say at 30 Hz, check the time, and update the label only if the time has changed enough to change the label (one second).
The interval you are passing is in seconds:
http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSTimer_Class/Reference/NSTimer.html
My guess is that it is getting called immediately, and then every 1 second afterwards, since you are passing 1 second as the timer interval. Try passing something like 1.0/20.0 to update at a higher frame rate.
Ii am trying to get date and time using date but when i run application it takes first time executed application time and date in short time is not changed.
NSDate *StrDate = [NSDate date];
NSDateFormatter *Dateformat = [[NSDateFormatter alloc]init];
[Dateformat setDateFormat:#"DD-MM-YYYY"];
NSMutableString *DateStr = [Dateformat stringFromDate:StrDate];
[UserCntrl.timeDisplay setText:DateStr];
[Dateformat setDateFormat:#"HH:MM"];
NSMutableString *timeStr=[Dateformat stringFromDate:StrDate];
Place a scheduled timer in your uiview did show (or did load) method:
[NSTimer scheduledTimerWithTimeInterval:1.0f // 1 second
target:self
selector:#selector(updateTime:)
userInfo:nil
repeats:YES];
Then, put this method in your View Controller:
- (void) updateTime:(id)sender
{
NSDate *StrDate = [NSDate date];
NSDateFormatter *Dateformat = [[NSDateFormatter alloc]init];
[Dateformat setDateFormat:#"DD-MM-YYYY HH:mm:SS"];
NSMutableString *DateStr = [Dateformat stringFromDate:StrDate];
[UserCntrl.timeDisplay setText:DateStr]; // or whatever code updates your timer. I didn't check this for bugs.
}
This will call the "updateTime:" method once a second, updating your controller.
[NSDate date] makes a date object of the time you call it. You must call it again to update the date. In other words, you must do StrDate = [NSDate date]; whenever you want to get the current date in your method.
You have a bug in your code:
Instead of
[Dateformat setDateFormat:#"HH:MM"];
it should be
[Dateformat setTimeFormat:#"HH:MM"];
I have implemented a simple clock like so:
- (void)runTimer {
timer = [NSTimer scheduledTimerWithTimeInterval:1.0
target:self
selector:#selector(showActivity)
userInfo:nil
repeats:YES];
}
- (void)showActivity {
NSDateFormatter *df = [[[NSDateFormatter alloc] init] autorelease];
NSDate *date = [NSDate date];
[df setDateFormat:#"HH:mm"];
[clock setFont:digitalFont];
[clock setText:[df stringFromDate:date]];
}
It's basiclly just a task that is run every second to update the time in a UILabel. Now what if I would like to extend this clock to react on certain times, just like a alarm clock.
Continously checking the value of NSDate seems battery intensive. How would I do this?
The simplest way to achieve this? Just have another NSTimer that is set to fire at the time of the alarm.
NSTimer* myTimer = [[NSTimer alloc] initWithFireDate:(NSDate *)date
interval:(NSTimeInterval)seconds
target:(id)target
selector:(SEL)aSelector
userInfo:(id)userInfo
repeats:(BOOL)repeats];
You can use initWithFireDate method