Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
273 views
in Technique[技术] by (71.8m points)

html - Conversion 12-hour to 24-hour format with javascript

I am trying to create a simple clock with javascript in 24-hour format. As far as i've come i only managed to get a 12-hour format. The script is really simple actually, here what i've got:

<div id="updatetime"></div>
<script>
        setInterval(function(){
        var d = new Date();
        var curr_hour = d.getHours();
        var curr_minute = d.getMinutes() + 1;
        document.getElementById("updatetime").innerHTML = curr_hour + ":" + curr_minute;
    }, 1000);
</script>

as for my question: How do i convert the 12-hour output to a 24-hour output while still keeping it simple. Only the hours and minutes are needed.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Date().getHours() does return the time in 24-hour format. To get 12-hour time from it, one simply uses the modulus operator (Date().getHours() % 12).

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/getHours

You should check that your clock is properly set and that it is past noon in your time zone.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...