Having milliseconds in my timer in Objective-C - objective-c

I'm doing a stopwatch using a youtube tutorial. The problem is that I want milliseconds in my timer but the tutorial only shows how to get seconds and minutes. I would like to get the milliseconds displayed like the minutes and seconds, but I've got no idea how to do it.
How to get milliseconds using this code?
#implementation ViewController {
bool start;
NSTimeInterval time;
}
- (void)viewDidLoad {
[super viewDidLoad];
self.display.text = #"0:00";
start = false;
}
- (void) update {
if ( start == false ) {
return;
}
NSTimeInterval currentTime = [NSDate timeIntervalSinceReferenceDate];
NSTimeInterval elapsedTime = currentTime - time;
int minutes = (int) (elapsedTime / 60.0);
int seconds = (int) (elapsedTime = elapsedTime - (minutes * 60));
self.display.text = [NSString stringWithFormat:#"%u:%02u", minutes, seconds];
[self performSelector:#selector(update) withObject:self afterDelay:0.1];
}

According to the docs, "NSTimeInterval is always specified in seconds; it yields sub-millisecond precision over a range of 10,000 years." So all you need to do is extract the milliseconds from your elapsedTime variable and then format your text again so that it includes milliseconds. It might looks something like this:
NSInteger time = (NSInteger)elapsedTime;
NSInteger milliseconds = (NSInteger)((elapsedTime % 1) * 1000);
NSInteger seconds = time % 60;
NSInteger minutes = (time / 60) % 60;
//if you wanted hours, you could do that as well
//NSInteger hours = (time / 3600);
self.display.text = [NSString stringWithFormat: "%ld:%ld.%ld", (long)minutes, (long)seconds, (long)milliseconds];

Related

Objective-c stringWithFormat Timer [duplicate]

This question already has answers here:
iOS Format String into minutes and seconds
(7 answers)
Closed 8 years ago.
I am trying to get a timer to show the counter like this "00:00:00". Here is my current code. I have been trying to get it to work using the stringWithFormat which should be easy but I guess I will have to set up the formats separately. Do you guys have any idea on how to do this?
- (void)TimerCount {
CountNumber = CountNumber + 1;
TimerDisplay.text = [NSString stringWithFormat:#"Hour: %0*i", length, hour];
}
- (void)timerCount {
{
CountNumber = CountNumber + 1;
NSInteger seconds = CountNumber % 60;
NSInteger minutes = (CountNumber / 60) % 60;
NSInteger hours = (CountNumber / 3600);
TimerDisplay.text = [NSString stringWithFormat:#"%i:%02i:%02i", hours, minutes, seconds];
}
Try the above code.
And configure this method to be fired every second.
In viewDidLoad
NSTimer *counterTimer = [NSTimer scheduledTimerWithTimeInterval:1.0
target:self
selector:#selector(timerCount)
userInfo:nil
repeats:YES];
[[NSRunLoop mainRunLoop] addTimer: counterTimer forMode:NSRunLoopCommonModes];
And keep the counterTimer as an iVar to keep it alive until the VC is dealloced, if you are using ARC.
- (void)TimerCount
{
CountNumber++;
NSString *time = [[NSString alloc] init];
NSUInteger seconds = CountNumber;
NSUInteger minutes = 0;
NSUInteger hours = 0;
if (seconds > 59) {
seconds -= 60;
minutes++;
if (seconds < 10) {
time = [NSString stringWithFormat:#":0%i",seconds];
} else time = [NSString stringWithFormat:#":%i",seconds];
}
if (minutes > 59) {
minutes -= 60;
hours++;
if (minutes < 10) {
time = [NSString stringWithFormat:#":0%i%#",minutes,time];
} else time = [NSString stringWithFormat:#":%i%#",minutes,time];
}
if (hours < 10) {
time = [NSString stringWithFormat:#"0%i%#",hours,time];
} else time = [NSString stringWithFormat:#"%i%#",hours,time];
}
NSString *time is the time.
Also NSTimer to call this method every second:
NSTimer *counterTimer = [NSTimer scheduledTimerWithTimeInterval:1.0
target:self
selector:#selector(timerCount)
userInfo:nil
repeats:YES];

convert float or double ( lengh of aufiofile ) in minute : seconds millisecond

Hello I tried to find a solution in Objective C to get the lenght of audio file included milliseconds.
at the moment I have only this code:
-(NSString *) DoubleToNSStringTime:(double)valore
{
NSNumber *theDouble = [NSNumber numberWithDouble:valore];
int inputSeconds = [theDouble intValue];
int hours = inputSeconds / 3600;
int minutes = (inputSeconds - hours * 3600 ) / 60;
int seconds = inputSeconds - hours * 3600 - minutes * 60;
NSString *theTime = [NSString stringWithFormat:#"%.2d:%.2d", minutes, seconds];
NSLog(#"TDoubleToNSStringTime= %#", theTime);
return theTime;
}
the Issue is this:
I would like to get more precise timePosition, Minutes : Seconds : Milleseconds
some of you has a solution?
Thanks
You don’t need to convert to NSNumber and back:
- (NSString *)DoubleToNSStringTime:(double)valore
{
NSInteger interval = (NSInteger)valore;
double milliseconds = (valore - interval) * 1000;
NSInteger seconds = interval % 60;
NSInteger minutes = (interval / 60) % 60;
minutes += (interval / 60);
return [NSString stringWithFormat:#"%02ld:%02ld:%3.0f", minutes, seconds, milliseconds];
}
That should print something like 60:45:789 for an input of 3645.789.

Time in milliseconds to typical time format

I need to convert time collected in milliseconds (e.g. 116124) to typical format of time like this: 03:12:32:04.
I don't know how to simple do it... Could you help me?
According to an Apple Dev forum linked here:
https://discussions.apple.com/thread/2350190?start=0&tstart=0
you have to do it yourself. Here is the function you can use that will return a formated string:
- (NSString *) formatInterval: (NSTimeInterval) interval{
unsigned long milliseconds = interval;
unsigned long seconds = milliseconds / 1000;
milliseconds %= 1000;
unsigned long minutes = seconds / 60;
seconds %= 60;
unsigned long hours = minutes / 60;
minutes %= 60;
NSMutableString * result = [NSMutableString new];
if(hours)
[result appendFormat: #"%d:", hours];
[result appendFormat: #"%2d:", minutes];
[result appendFormat: #"%2d:", seconds];
[result appendFormat: #"%2d",milliseconds];
return result;
}

countdown timer with minutes and seconds

i create a countdown timer that go from 10 to 0. i create a uilabel that shows the counter in seconds. now i want the label to show the counter minutes and second, like that: 00:00.
how can i do that?
here is my countdowncode:
-(void)countdown
{
countdownCounter -= 1;
countdown.text = [NSString stringWithFormat:#"%i", countdownCounter];
}
-(IBAction)strat:(id)sender
{
countdownCounter = 10;
countdownTimer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:#selector(countdown) userInfo:nil repeats:YES];
}
}
thanks!
This can be done using one time, and one label. Try using the following code:
int seconds = [countDown.text intValue] % 60;
int minutes = ([countDown.text intValue] / 60) % 60;
countDown.text = [NSString stringWithFormat:#"%2d:%02d", minutes, seconds];
Do it exactly the same way, just add another timer.
countdownTimer2 = [NSTimer scheduledTimerWithTimeInterval:60.0 target:self selector:#selector(countdown2) userInfo:nil repeats:YES];
-(void)countdown2
{
countdownCounterMinutes -= 1;
}
and change countdown to
-(void)countdown
{
countdownCounter -= 1;
countdown.text = [NSString stringWithFormat:#"%i%i", countdownCounterMinutes, countdownCounter];
}
for anyone who what the answer in the end i do it this way:
-(IBAction)start
{
timer = [NSTimer scheduledTimerWithTimeInterval:.01 target:self selector:#selector(updateTimer:) userInfo:nil repeats:YES];
}
-(void)updateTimer:(NSTimer *)timer {
currentTime -= 10 ;
[self populateLabelwithTime:currentTime];
if(currentTime <=0)
[timer invalidate];
}
- (void)populateLabelwithTime:(int)milliseconds {
seconds = milliseconds/1000;
minutes = seconds / 60;
hours = minutes / 60;
seconds -= minutes * 60;
minutes -= hours * 60;
NSString * result1 = [NSString stringWithFormat:#"%#%02d:%02d:%02d:%02d", (milliseconds<0?#"-":#""), hours, minutes, seconds,milliseconds%1000];
result.text = result1;
}
in viewDidLoad i set currentTime for the countdown time in milliseconds.
hope you understand...
I formatted the numbers (from float)with mins and seconds
it this way, thanks your answers helped. (hope this helps another)
- (void)ticTimer
{
self.current -= self.updateSpeed;
CGFloat progress = self.current / self.max;
[self populateLabelwithTimeFormatted:self.current];
/// TimeLabelNode.text = [NSString stringWithFormat:#"%f", progress];
// * Time is over
if (self.current <= self.min) {
[self stop];
_TimeLabelNode.text= #"time up!";
}
}
- (void)populateLabelwithTimeFormatted:(float)time {
//convert float into mins and seconds format
int mytime = (int) _current;
int seconds = mytime%60;
int minutes = mytime / 60 % 60;
NSString * result1 = [NSString stringWithFormat:#"%2d:%02d", minutes, seconds];
_TimeLabelNode.text = result1;
}

iOS timeout functionality not working properly

I added this code which functions as an auto timeout in my app. The userDefaults doubleForKey:#"timeoutLength" should be in minutes. For example, if value is 500, that should mean 500 minutes.
I keep seeming to be hitting the timout loop though even when it hasn't really been 500 + min. Is anything wrong in my code? Perhaps a minutes/seconds error etc.
[userDefaults setDouble:[[userContextDictionary valueForKey:#"autologout_idle_timeout"] doubleValue] forKey:#"timeoutLength"];
double timeDifference = ([[NSDate date] timeIntervalSince1970] - [userDefaults doubleForKey:#"Close Time"]) / 60;
if (timeDifference > [userDefaults doubleForKey:#"timeoutLength"]) {
NSLog(#"Timeout Hit");
} else {
NSLog(#"No Timeout");
}
Edit:
- (void)applicationDidEnterBackground:(UIApplication *)application {
[userDefaults setObject:[NSDate date] forKey:#"Close Time"];
}
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
[userDefaults setDouble:[[userContextDictionary valueForKey:#"autologout_idle_timeout"] doubleValue] forKey:#"timeoutLength"];
//This is an int like 500, or 600, etc.
NSDate *closeDate = [userDefaults objectForKey:#"Close Time"]
NSTimeInterval timeWhenClosedTimeInterval = [closeDate timeIntervalSince1970];
NSTimeInterval todayTimeInterval = [[NSDate date] timeIntervalSince1970];
NSTimeInterval timeDifference = ((todayTimeInterval - timeWhenClosedTimeInterval ) / 60);
if (timeDifference > [userDefaults doubleForKey:#"timeoutLength"]) {
NSLog(#"Timeout Hit");
} else {
NSLog(#"No Timeout");
}
return YES;
}
NSTimeInterval is expressed in seconds, not minutes.
Here's the Apple doc where it's described.
I'm not 100% certain what your ultimate problem with, but 500 seconds doesn't seem like nearly enough time.
In the meantime, I wrote up some changes to your code to demo for myself:
NSDate * yesterday = [[NSDate date] dateByAddingTimeInterval: (-1 * 60 * 60 * 24 )];
NSTimeInterval yesterdayTimeInterval = [yesterday timeIntervalSince1970];
NSTimeInterval todayTimeInterval = [[NSDate date] timeIntervalSince1970];
// this properly converts timeDifference in seconds to minutes
NSTimeInterval timeDifference = ((todayTimeInterval - yesterdayTimeInterval ) / 60);
NSLog( #"time difference is %4.2f", timeDifference );
which came up with 1400 minutes (divided by 60 minutes per hour = 24 hours).
My guess is there is some error with setting the NSUserDefaults values, or an error with your timeDifference calculation. Add this line and make sure you are actually setting the timeout length to 500:
NSLog(#"Timeout length: %f, close time: %f, time difference: %f", [userDefaults doubleForKey:#"timeoutLength"], [userDefaults doubleForKey:#"Close Time"], timeDifference);