2

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 ?

Poliquin
  • 2,937
  • 4
  • 28
  • 32
  • Do you try this lib http://momentjs.com/ – Farkhat Mikhalko Feb 24 '14 at 05:37
  • 4
    "following the W3C tutorial" - **NOPE**, I recognize that terrible quality code style, it most surely came from w3schools. W3Schools has absolutely no affiliation with W3C (http://w3fools.com/). On the other hand, MDN has some quite decent [tutorials](https://developer.mozilla.org/en-US/docs/Web/Tutorials). (just commenting in hopes to save a soul before it is too late) – Fabrício Matté Feb 24 '14 at 05:37
  • More on-topic, you will need to use the [Date](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date#Date_instances) instance methods, or momentjs. – Fabrício Matté Feb 24 '14 at 05:44
  • 2
    The output of *Date.prototype.toString* is entirely implementation dependent, you'll get different formats from different implementations. To get a particular format, you must do it yourself unless you wish to rely on ES5's [toISOString](http://ecma-international.org/ecma-262/5.1/#sec-15.9.5.43). But likely that isn't what you want. – RobG Feb 24 '14 at 05:46

1 Answers1

6

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)(?=:|\.)

Regular expression visualization

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.

elixenide
  • 44,308
  • 16
  • 74
  • 100