Converting seconds to English readable time duration

In a project I’m working on I get the number of seconds since the device was turned on and I need to display a message to the user similar to this: System uptime is 2 years, 1 month, 13 days, 1 hour and 15 seconds.

I figured that since showing System uptime is common to many websites it would be easy to find someone who had already written some code to do the conversion. After about 15 minutes of searching I hadn’t found anything and figured I could have written the code myself in that time. ( It actually took closer to 30 minutes to write the code because John Wilker stole my mojo and I was feeling pretty stupid. )

view source

Trouble with time

So I lied. It ended up taking hours to get the code to work just right, at least mostly right.

There were losts of little things that I had to accomodate. Like if the time output ends with hours then it needs to say, “blah, blah, blah and some hours.” Originally I only took into account the “and” going before the seconds. But if there are no seconds then … you get my meaning.

Oh, and adding a space in some places to the output string turned out to be harder than I thought it would be. But after messing with output for a while I think I got it.

Time is an illusion, lunch-time doubly so

But then the issue came up: how many seconds are there in a year, or whatever. There are lots of different ways to measure time durations. Turns out we’re pretty well set for things like minutes, hours, and days. Beyond that it starts getting messy.

The way my code works is to take the number of seconds you input and create a date starting that many seconds after January 1, 1970. It’s then doing conversions to see how many years, month, days, etc. after that date. Which is probably going to be an approximation of what you really want. But the problem is that I don’t know what you really want. It could be that you want to measure time before or after right now. That would be a different algorythm. If that’s what you need then you have my source to start from. This solution works for my current need and I’ll bet it would work for Douglas Adams, if he needed such a thing.

If you know of some standards that are used in time calculations, such as this I’d love to hear about it in the comments. Or anything else you might have to share on the matter.