Javascript converts seconds to HH-MM-SS time format, hh-mm-ss time format
Recently I am writing an html5 game. It is inevitable that the timing function will be used in the game. I simply set a passedTime variable. In the game loop, there are no 60 frames + + once (FPS = 60 ). Then it is necessary to convert passeTime to the time displayed in the format. Although this computer time method is not very accurate (because not any machine can ensure that it can update 60 times in any second), but the current computer efficiency is very high, coupled with broswer progress, unless you use an antique host.
In fact, there are many methods. Here I simply use the following two functions:
function getTimeFromSeconds(totalSeconds) { if (totalSeconds < 86400) { var dt = new Date("01/01/2000 0:00"); dt.setSeconds(totalSeconds); return formatTime(dt); } else { return null; }}function formatTime(dt) { var h = dt.getHours(), m = dt.getMinutes(), s = dt.getSeconds(), r = ""; if (h > 0) { r += (h > 9 ? h.toString() : "0" + h.toString()) + ":"; } r += (m > 9 ? m.toString() : "0" + m.toString()) + ":" r += (s > 9 ? s.toString() : "0" + s.toString()); return r;}
It can be used as follows:
$("#game_passed_time").text(getTimeFromSeconds(gamePassedTime));
In this way, the time can be displayed. Haha, I hope that this simple thing will not waste you a lot of time.
Frontend technical exchange group: 139761568