LearnFast.Ninja

JavaScript current time in milliseconds as string

Create instance of Date class. Use the date get functions to get the current time e.g. get the current in millisecond. Print the time as string. In the working code example we create variables for Hours, Minutes, Seconds and Milliseconds. When the user click the button we execute the function myGetTime to get the current time and we print the time in alert box.

Step 1: Create instance of Date class. 
var myTime = new Date();
 
Step 2: Use the date get functions to get the current time e.g. get the current in millisecond. 
var ms = myTime.getMilliseconds();
 
Step 3: Print the time as string. 
alert("Time: " + hh + ":" + mm + ":" + ss + " Milliseconds: " + ms);

// or

alert(ms.toString());

 
Working code example: 

<html>

<head>

    <title>javascript print time</title>

    <script type="text/javascript">

        function myGetTime() {

            var myTime = new Date();

            var hh = myTime.getHours();

            var mm = myTime.getMinutes();

            var ss = myTime.getSeconds();

            var ms = myTime.getMilliseconds();

            alert("Time: " + hh + ":" + mm + ":" + ss + " Milliseconds: " + ms);

        }

    </script>

</head>

<body>

    <button onclick="myGetTime()">Click Me to show time.</button>

</body>

</html>


Result:


Tags

javascript

time milliseconds date