Converting seconds into hours, minutes, and seconds - ios

I am making a stopwatch app. I am counting the time elapsed since the app was in the background, so that I can add it on to the stopwatch time when the app returns to the foreground. I have this code which is called when an NSNotification is sent to my StopwatchViewController with the elapsed time in seconds. I am trying to convert the seconds into hours, minutes and seconds:
-(void)newMessageReceived:(NSNotification *) notification
{
elapsedTime = [[notification object] intValue];
elapsedHours = elapsedTime / 3600;
elapsedTime = elapsedTime - (elapsedTime % 3600);
elapsedMinutes = elapsedTime / 60;
elapsedTime = elapsedTime - (elapsedTime % 60);
elapsedSeconds = elapsedTime;
secondInt = secondInt + elapsedSeconds;
if (secondInt > 59) {
++minuteInt;
secondInt -= 60;
}
minuteInt = minuteInt + elapsedMinutes;
if (minuteInt > 59) {
++hourInt;
minuteInt -= 60;
}
hourInt = hourInt + elapsedHours;
if (hourInt > 23) {
hourInt = 0;
}
}
The notification object is assigned to elapsedTime, but that is it; elapsedHours/minutes/seconds all stay at 0, and elapsedTime stays the same. Why isn't it working?

This approach seems overly complicated and error prone.
Why not just record the start time (as NSTimeInterval or NSDate) and subtract that from the current time to get the elapsed seconds?

You are subtracting off the wrong part from elapsedTime. You should be subtracting the hours not the remainder:
elapsedTime = elapsedTime - (elapsedTime / 3600) * 3600;
or you could use the equivalent calculation:
elapsedTime = elapsedTime % 3600;

Convert seconds in h m s with the usage of type conversion float to int
seconds = 111222333 # example
h = (seconds/60/60)
m = (h-int(h))*60
s = (m - int(m))*60
Check the result
print(f'{h:.0f} {m:.0f} {s:.0f}')

Related

Issue in finding time difference

In my app, I want to know the difference between:
the total hours worked in the week(54.30 hours)
and
the total hours worked on a specific day(10.45 hours)
For example, I want to know the value of (54.30 hours - 10.45 hours) in
hours. Since the total hours of week is greater than 24 hrs, I
couldn't convert it into NSDate.
Use this 2 functions,this will help you
The below function will return total seconds from the hour string
- (NSNumber *)secondsForTimeString:(NSString *)string {
NSArray *components = [string componentsSeparatedByString:#"."];
NSInteger hours = [[components objectAtIndex:0] integerValue];
NSInteger minutes = [[components objectAtIndex:1] integerValue];
//NSInteger seconds = [[components objectAtIndex:2] integerValue];
return [NSNumber numberWithInteger:(hours * 60 * 60) + (minutes * 60)];
}
And below function will return formatted time from seconds
- (NSString *)timeFormatted:(int)totalSeconds {
//int seconds = totalSeconds % 60;
int minutes = (totalSeconds / 60) % 60;
int hours = totalSeconds / 3600;
return [NSString stringWithFormat:#"%02d.%02d",hours, minutes];
}
Now you can calculate the remaining hours like this :
int diffrence =[[self secondsForTimeString:#"54.30"] intValue] - [[self secondsForTimeString:#"10.45"] intValue];
NSLog(#"Remaining Hours - %#",[self timeFormatted:diffrence]);

i want to manage time for currently playing song,i need block for that

I want to make player where i can play song and manage time for that song. I need a method with block where three things returned
1)Elapsed play time
2)Remaining time
3)Percentage of Elapsed time.
Block should look like
andBlock:^(int percentage, CGFloat elapsedTime, CGFloat timeRemaining, NSError *error, BOOL finished){
NSInteger ti = (NSInteger)timeRemaining;
NSInteger seconds = ti % 60;
NSInteger minutes = (ti / 60) % 60;
NSInteger eti = (NSInteger)elapsedTime;
NSInteger eseconds = eti % 60;
NSInteger eminutes = (eti / 60) % 60;
}
I need simple method for time management with above block.

iOS timer/wage calculator

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.. :)

iOS Format String into minutes and seconds

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];

How to limit float Value in iOS

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.

Resources