Can anyone please tell me how to display milliseconds in this piece of code?
-(void)updateViewForPlayerInfo:(AVAudioPlayer*)p {
countdownTimer = [NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:#selector(updateTimeLeft)userInfo:p repeats:YES];
}
- (void)updateTimeLeft {
NSTimeInterval timeLeft = player.duration - player.currentTime;
int min=timeLeft / 60;
int sec=lroundf(timeLeft) % 60;
durationLabel.text = [NSString stringWithFormat:#"-%02d:%02d",min,sec,nil];
}
[NSTimer scheduledTimerWithTimeInterval:0.0167 target:self selector:#selector(updateTimer) userInfo:nil repeats:YES];
-(void)updateTimer {
countDownTotalTimer++;
TotalTime.text=[self timeFormatted:countDownTotalTimer];
}
- (NSString *)timeFormatted:(int)milli
{
int millisec = ((milli) % 60)+39;
int sec = (milli / 60) % 60;
int min = milli / 3600;
return [NSString stringWithFormat:#"%02d:%02d:%02d",min, sec, millisec];
}
If any wants milliseconds to max 60 than edit this line
int millisec = ((milli) % 60)+39;
to
int millisec = ((milli) % 60);
I don't understand. Don't you just have to create a new variable for the milliseconds?
NSInteger milliseconds = (sec * 1000);
durationLabel.text = [NSString stringWithFormat:#"-%02d:%02d.%04d",min,sec, milliseconds, nil];
I think this is the simplest solution:
durationLabel.text = [NSString stringWithFormat:#"-%02d:%06.3f",
(int)(timeLeft / 60), fmod(timeLeft, 60)];
That formats the time as MM:SS.sss. If you really want it as MM:SS:sss (which I don't recommend), you can do this:
durationLabel.text = [NSString stringWithFormat:#"-%02d:%02d:%03.0f",
(int)(timeLeft / 60), (int)fmod(timeLeft, 60), 1000*fmod(timeLeft, 1)];
Note that stringWithFormat: does not require nil at the end of its argument list.
Related
I have a button on which i have placed a UITapGestureRecognizer. When i tap on that button, i call a method that starts the time.
My question is, i am able to get the timer string on a label. But the timer starts from current date-time, and i want to start the timer always from zero(like a countdown timer). Here below is my code for timer.
-(IBAction)micPressed{
if (gestureRecognizer.state==UIGestureRecognizerStateBegan) {
gestureRecognizer.view.alpha=0.2f;
[label setHidden:NO];
if (!_timer) {
_timer = [NSTimer scheduledTimerWithTimeInterval:0.1f
target:self
selector:#selector(_timerFired:)
userInfo:nil
repeats:YES];
}
}
else{
[label setHidden:YES];
gestureRecognizer.view.alpha=10.2f;
if ([_timer isValid]) {
[_timer invalidate];
}
_timer = nil;
}
}
- (void)_timerFired:(NSTimer *)timer {
NSDateFormatter *dateformatter=[[NSDateFormatter alloc]init];
[dateformatter setDateFormat:#"mm:ss:SSS"];
NSString *dateInStringFormated=[dateformatter stringFromDate:[NSDate dateWithTimeIntervalSinceNow:0]];
NSLog(#"%#",dateInStringFormated);
[label setText:dateInStringFormated];
}
Please can anyone suggest me the solution. Any help is appreciated.
Your code should be like,
NSDateFormatter *dateformatter=[[NSDateFormatter alloc]init];
[dateformatter setDateFormat:#"mm:ss:SSS"];
NSString *dateInStringFormated=[dateformatter stringFromDate:[dateformatter dateFromString:#"00:00:000"]];
NSLog(#"test : %#",dateInStringFormated);
I have just chage [NSDate dateWithTimeIntervalSinceNow:0] with [dateformatter dateFromString:#"00:00:000"].
It will start with zero always.
Update :
I think you want something like timer that update minutes,seconds and milliseconds as i understand your question now. You can achieve it something like,
Schedule timer like,
NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:0.01 target:self selector:#selector(updateTimer) userInfo:nil repeats:YES];
Now your updateTimer should be like,
-(void)updateTimer{
static double counter = 0;
static int counter2 = 0;
int seconds = (int)counter % 60;
int minutes = ((int)counter / 60) % 60;
NSLog(#"%02d:%02d:%03d",minutes,seconds,counter2); // This should be your labels text that updating continuously
counter = counter + 0.01;
counter2++;
if (counter2 == 100) {
counter2 = 0;
}
}
Hope this will help :)
The problem is you are starting your timer from current time itself. To make a like countdown timer. You need to do the following:
Take an int named Counter and intialize it from 0
Fire your NSTimer and at that time increase the counter
Display the counter value in the UILabel text.
Once your NSTimer stops, again make it to 0.
That's it! This is how you can achieve the desired result.
Code:
int counter = 0;
- (void)_timerFired:(NSTimer *)timer {
counter++;
}
Once NSTimer is invalidate again make it to counter = 0
Remember the time when you have started the timer:
_startDate = [NSDate date];
_Timer = ...
Then use the time interval since the start date in your _timerFired method:
NSDateComponentsFormatter *formatter = [[NSDateComponentsFormatter alloc] init];
NSString *dateInStringFormatted = [formatter stringFromTimeInterval:[[NSDate date] timeIntervalSinceDate:_startDate]];
I'm having a problem when I'm trying to display the score as a highscore.
This is my code for getting the time ont the label on the correct format.
- (void)populateLabelwithTime:(int)milliseconds {
int seconds = milliseconds / 1000;
int minutes = seconds / 60;
int hours = minutes / 60;
seconds -= minutes * 60;
minutes -= hours * 60;
resultScoreLabel.text = [NSString stringWithFormat:#"%ds:%dms",seconds, milliseconds%1000];
if (currentTime > highScore) {
[[NSUserDefaults standardUserDefaults] setInteger:currentTime forKey:#"highscore"];
resultHighScoreLabel.text = [NSString stringWithFormat:#"%i",highScore +10];
}
else {
}
}
-(void)scoring {
currentTime += 10;
[self populateLabelwithTime:currentTime];
highScore = [[NSUserDefaults standardUserDefaults] integerForKey:#"highscore"];
}
The score format appears correct.
score is: 1s:186ms
but the highscore appears wrong
Your highscore is: 1186
know that this line is wrong
resultHighScoreLabel.text = [NSString stringWithFormat:#"%i",highScore +10];
but I cannot figure how to make it work
any suggestions??
This is the quickfix:
int newHighscore = highScore+10;
int seconds = ((int)floor((newHighscore)/1000));
int milliseconds = newHighscore%1000;
resultHighScoreLabel.text = [NSString stringWithFormat:#"%is:%ims",seconds,milliseconds];
However I would highly recommend to change the way you handle the highscore
I'm making a timer that takes an hourly wage input and tracks how much money is made per second. The formatting on the timer works just fine but once the pennies hits 99 it zeros out and only adds to the dollars. Here is what I've got.
seconds = (int) (elapsedTime = (elapsedTime - (minutes *60)));
pennies = seconds * (ratePerSecond * 100);
if(pennies > 99){
dollars++;
pennies = 0;
}
self.moneyDisplay.text = [NSString stringWithFormat: #"$%02d.%02d", dollars, pennies];
Try this:
seconds = (int) (elapsedTime = (elapsedTime - (minutes *60)));
pennies = seconds * (ratePerSecond * 100);
float dollars = pennies / 100.0;
self.moneyDisplay.text = [NSString stringWithFormat: #"$%.2f", dollars];
or:
seconds = (int) (elapsedTime = (elapsedTime - (minutes *60)));
pennies = seconds * (ratePerSecond * 100);
int cents = pennies % 100;
int dollars = pennies / 100;
self.moneyDisplay.text = [NSString stringWithFormat: #"$%02d.%02d", dollars, cents];
May be you want to do this (without if condition):
dollars = pennies / 100;
pennies = pennies % 100;
self.moneyDisplay.text = [NSString stringWithFormat: #"$%02d.%02d", dollars, pennies];
Note that: The operands of the % operator shall have integer type.
Hope this helps.. :)
I am receiving a string from the YouTube JSONC api, but the duration is coming as a full number i.e 2321 instead of 23:21 or 2 instead of 0:02. How would I go about fixing this?
JSON C
EDIT:
int duration = [videos valueForKey:#"duration"];
int minutes = duration / 60;
int seconds = duration % 60;
NSString *time = [NSString stringWithFormat:#"%d:%02d", minutes, seconds];
Assuming the duration value is really the duration in seconds, then you can calculate the number of minutes and seconds and then format those into a string.
int duration = ... // some duration from the JSON
int minutes = duration / 60;
int seconds = duration % 60;
NSString *time = [NSString stringWithFormat:#"%d:%02d", minutes, seconds];
You should use DateComponentsFormatter if the duration is intended to be user-facing:
let formatter = DateComponentsFormatter()
formatter.allowedUnits = [ .minute, .second ]
formatter.zeroFormattingBehavior = [ .pad ]
let formattedDuration = formatter.string(from: duration)!
Try this very optimized
+ (NSString *)timeFormatConvertToSeconds:(NSString *)timeSecs
{
int totalSeconds=[timeSecs intValue];
int seconds = totalSeconds % 60;
int minutes = (totalSeconds / 60) % 60;
int hours = totalSeconds / 3600;
return [NSString stringWithFormat:#"%02d:%02d:%02d",hours, minutes, seconds];
}
int sec = diff;//INFO: time in seconds
int a_sec = 1;
int a_min = a_sec * 60;
int an_hour = a_min * 60;
int a_day = an_hour * 24;
int a_month = a_day * 30;
int a_year = a_day * 365;
NSString *text = #"";
if (sec >= a_year)
{
int years = floor(sec / a_year);
text = [NSString stringWithFormat:#"%d year%# ", years, years > 0 ? #"s" : #""];
sec = sec - (years * a_year);
}
if (sec >= a_month)
{
int months = floor(sec / a_month);
text = [NSString stringWithFormat:#"%#%d month%# ", text, months, months > 0 ? #"s" : #""];
sec = sec - (months * a_month);
}
if (sec >= a_day)
{
int days = floor(sec / a_day);
text = [NSString stringWithFormat:#"%#%d day%# ", text, days, days > 0 ? #"s" : #""];
sec = sec - (days * a_day);
}
if (sec >= an_hour)
{
int hours = floor(sec / an_hour);
text = [NSString stringWithFormat:#"%#%d hour%# ", text, hours, hours > 0 ? #"s" : #""];
sec = sec - (hours * an_hour);
}
if (sec >= a_min)
{
int minutes = floor(sec / a_min);
text = [NSString stringWithFormat:#"%#%d minute%# ", text, minutes, minutes > 0 ? #"s" : #""];
sec = sec - (minutes * a_min);
}
if (sec >= a_sec)
{
int seconds = floor(sec / a_sec);
text = [NSString stringWithFormat:#"%#%d second%#", text, seconds, seconds > 0 ? #"s" : #""];
}
NSLog(#"<%#>", text);
Here is the great code I finds for this
int duration = 1221;
int minutes = floor(duration/60)
int seconds = round(duration - (minutes * 60))
NSString * timeStr = [NSString stringWithFormat:#"%i:%i",minutes,seconds];
NSLog(#"Dilip timeStr : %#",timeStr);
And the output will belike this
Dilip timeStr : 20:21
You can subString the 2321 and get the first string as 23 and the second as 21 and convert them to int. Also check for the length of the text:
if (text.length < 4)
//add zeros on the left of String until be of length 4
Objective C:
NSDateComponentsFormatter * formatter = [[NSDateComponentsFormatter alloc]init];
[formatter setUnitsStyle:NSDateComponentsFormatterUnitsStyleShort];
[formatter setAllowedUnits:NSCalendarUnitSecond | NSCalendarUnitMinute];
[formatter setZeroFormattingBehavior:NSDateComponentsFormatterZeroFormattingBehaviorPad];
return [formatter stringFromTimeInterval:duration];
Now i am trying to get the length of Songs in iOS.
- (NSString *)returnofTotalLength
{
float duration = [[self.player.nowPlayingItem valueForProperty:MPMediaItemPropertyPlaybackDuration] floatValue]/60.0f;
NSString *length = [NSString stringWithFormat:#"%.2f",duration];;
NSString *totalLength = [length stringByReplacingOccurrencesOfString:#"." withString:#":"];
return totalLength;
}
above codes is the total length of song that show like 5:90.
You know that 5:90 can't be true because 60 seconds is 1 minute.
It's should be 6:30.
So i want to limit that value for 1 minute (60 seconds).
How can i do it Please help me?
Thanks.
This is simple math. Pseudocode:
minutes = (int)(seconds / 60);
rest = seconds % 60;
result = minutes:rest
Objc:
int seconds = 150;
int minutes = (int)(seconds / 60);
int rest = seconds % 60;
return [NSString stringWithFormat:#"%i:%i", minutes, rest];
do following :
min=(int)duration/60;
sec=duration%60;
than append minutes and second
If your time crosses to hours then you can go for this :
NSInteger seconds = duration % 60;
NSInteger minutes = (duration / 60) % 60;
NSInteger hours = duration / (60 * 60);
NSString *result = nil;
result = [NSString stringWithFormat:#"%02ld:%02ld:%02ld", hours, minutes, seconds];
I just got answer for my own question.
Thanks for other answers. :)
NSTimeInterval currentProgress = [[self.player.nowPlayingItem valueForProperty:MPMediaItemPropertyPlaybackDuration] floatValue];
float min = floor(currentProgress/60);
float sec = round(currentProgress - min * 60);
NSString *time = [NSString stringWithFormat:#"%02d:%02d", (int)min, (int)sec];
return time;
That will return NSString with Complete Format.