JavaScript > Date

SetTime() Method in JavaScript

How to set a date and time by adding or subtracting a specified number of milliseconds to UTC standard time in JavaScript?


By using setTime() method we can set a date and time by adding or subtracting a specified number of milliseconds to UTC standard time.

EXAMPLE: In this example we are adding milliseconds to Jan 1st, 1970 (UTC standerd time), to set a date and time. 

<p>Click the below button to set the Time by adding the milliseconds.</p>
<input type="button" value="Click" onclick="myDate()" />
<p id="myId"></p>

<script>
    function myDate() {
        var a = new Date();
        a.setTime(1844282527852); //*adding milliseconds & set date and time*//
        document.getElementById("myId").innerHTML = a;
    }
</script>

In the above code snippet we have given Id as "myId"to the second <p> element in the HTML code. There is a function myDate() in the<script>block which is connected to the Onclick of the HTML button. The document.getElementById("myId")returns the element that has Id"id=myID" in the HTML page. We need to set a date and time by adding or substracting number of milliseconds to the UTC time (1st January, 1970), for that we are using setTime() method. We are adding "1844282527852" milliseconds to the UTC date and time. Onclick of the button "Click" in the HTML code fires the function myDate() in the <script> block, at the same time setTime() method adds the specified number of milliseconds to UTC standerd time (Jan 1st, 1970) and set a time & date after adding the milliseconds and gives the output.

OUTPUT

 

NOTE: After adding "184428252852" milliseconds to the UTC standerd time, the details are as follow,

Date: 11-June-2028.

Time: 2:12:07 (IST).

Day: Sunday.

 Views: 7964 | Post Order: 125



Write for us






Hosting Recommendations