简体   繁体   中英

Display hh:mm:ss.msmsms in javascript

I am following the W3Schools tutorial on javascript Date object and trying to display the time in hh:mm:ss.msmsms format.

<!DOCTYPE html>
<html>
<body>

<p id="demo">Click the button to display a date after changing the hours, minutes, and seconds.</p>

<button onclick="myFunction()">Try it</button>

<script>
function myFunction()
{
var d = new Date();
d.setHours(07,01,01,312);
var x = document.getElementById("demo");
x.innerHTML=d;
}
</script>

</body>
</html>

I was expecting 07:01:01.312 (as in hh:mm:ss.msmsms) but it shows

Sun Feb 23 2014 07:01:01 GMT-0600 (CST)

How can i get javascript to displace 07:01:01.312 ?

You have to build the string in question yourself:

x.innerHTML = (d.getHours()+':'+d.getMinutes()+':'+d.getSeconds()+'.'+d.getMilliseconds()).replace(/(^|:)(\d)(?=:|\.)/g, '$10$2');
// result: 07:01:01.312

We build the string (hours, minutes, seconds, milliseconds), then run replace to add a zero in front of any lone digits.

Edit: Here's an explanation of the regular expression I used in .replace() above:

(^|:)(\d)(?=:|\.)

正则表达式可视化

Debuggex Demo

Basically, it looks for (1) either the start of the string or a : , then (2) a single digit, then (3) another : or a . . It then replaces (1) and (2) with whatever matched (1), 0 , and the digit that matched (2). The /g means "do this globally." So, 7:1:1.312 becomes 07:01:01.312 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM