Javascript converts seconds to HH-MM-SS time format, hh-mm-ss time format

Source: Internet
Author: User

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


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.