Display timer correctly (3:45) based on number of seconds

- 1 answer


I'm developing a website and using socket.io.I have items auctions and in my database I have set the time(unix timestamp) for each auction to end. When users bid on that item, if is there less than 20 seconds to end then the time on the database must change for it to get back to 20 seconds remaining. On every new bid the seconds left will be 20 seconds. So with that said, that's what we have:

  • The client connects and gets the final time from server(server gets it from database and tells the client)

  • The client then must show the timeleft (currently showing xxx seconds) ( here's where I need help.)

  • When user bids, the server checks if the timer is under 20 seconds and if it is, the server adds UNIX_TIMESTAMP(NOW())+20 on database.

Long story short, what I need is the javascript to calculate the database stored timestamp minus the current unix timestamp (which it already does) and then turn it into 0:00... Let's say database time - current time equals 600 seconds, how should I do to turn it into 5:00 output? Thank You!

SOLUTION: I'm sorry guys, this was really simple to solve and I found a solution after some advice. For those who are facing the same "problem" here is the solution I found and it couldn't be more simple

var time= 300;
var minutes = "0" + Math.floor(time / 60);
var seconds = "0" + (time - minutes * 60);
return minutes.substr(-2) + ":" + seconds.substr(-2);

Credits to the user who gave this answer on this thread: Javascript seconds to minutes and seconds




You would modulo the seconds by 60. Put the result in minutes and the remainder in seconds. Make sure you account for leading 0's. There might be some kind of string format for this but I don't know off the top of my head. Moment.js would make this very simple as well though, just take the current time, add the seconds, and use one of it's format options with m:ss.

There are a lot of examples on here to reference for moment.js. Here's an example: How to convert seconds to HH:mm:ss in moment.js

source: stackoverflow.com