iOS Convert Seconds into hours,minutes and seconds

Hi all,

In building iPhone applications you may have come across situations that you count some time in seconds, but wish to let the user view it in a more readable format such as 1 hour 38 minutes and 44 seconds. Here is a piece of code that I wrote if you need to get this done in your code.


- (NSString *)timeFormatted:(int)totalSeconds
{
    int seconds = totalSeconds % 60;
    int minutes = (totalSeconds / 60) % 60;
    int hours = totalSeconds / 3600;
   
    NSString *timeString =@"";
    NSString *formatString=@"";
    if(hours > 0){
        formatString=hours==1?@"%d hour":@"%d hours";
        timeString = [timeString stringByAppendingString:[NSString stringWithFormat:formatString,hours]];
    }
    if(minutes > 0 || hours > 0 ){
        formatString=minutes==1?@" %d minute":@" %d minutes";
        timeString = [timeString stringByAppendingString:[NSString stringWithFormat:formatString,minutes]];
    }
    if(seconds > 0 || hours > 0 || minutes > 0){
        formatString=seconds==1?@" %d second":@" %d seconds";
        timeString  = [timeString stringByAppendingString:[NSString stringWithFormat:formatString,seconds]];
    }
    return timeString;
      
}

This code checks to see if the number of hours, minutes or seconds is equal to one and displays either hour/hours, minute/minutes or second/seconds accordingly.

Have fun coding, guys & gals !!!

Comments

Aliya Manasa said…
Excellant post!!!. The strategy you have posted on this technology helped me to get into the next level and had lot of information in it.
python Training in Pune
python Training in Chennai
python Training in Bangalore
Unknown said…
Thank you for allowing me to read it, welcome to the next in a recent article. And thanks for sharing the nice article, keep posting or updating news article.
Best Devops Training in pune
Devops Training in Bangalore
Power bi training in Chennai
priya said…
Wow it is really wonderful and awesome thus it is very much useful for me to understand many concepts and helped me a lot. it is really explainable very well and i got more information from your blog.
Data Science Training in Indira nagar
Data Science training in marathahalli
Data Science Interview questions and answers
Data Science training in btm layout
Data Science Training in BTM Layout
Data science training in bangalore
Truly mind blowing blog went amazed with the subject they have developed the content. These kind of posts really helpful to gain the knowledge of unknown things which surely triggers to motivate and learn the new innovative contents. Hope you deliver the similar successive contents forthcoming as well.

data science certification in bhilai

Popular posts from this blog

Encrypt and Decrypt Images Using Java

Build your own Network sniffer

ASP Response.Write newline