JavaScript > Date

ToISOString() Method in JavaScript

How to convert a date object into a string using the ISO standard in JavaScript?

By using toISOString() method we can convert a date object into a string using the ISO standard.

ISO standard: ISO 8601 is an internationally accepted way to represent dates and times using numbers.

<p>Click the below button to convert the date of a date object into string, using ISO standard.</p>
<input type="button" value="Click" onclick="myDate()" />
<p id="myId"></p>

    var a = new Date();  //* Returns the date & time as per the internet network *//
    alert(a);  //* Displays the Var A result in the alert box *//

    function myDate() {
        var r = a.toISOString(); //* Converts a date object into string using ISO standard *//
        document.getElementById("myId").innerHTML = r;

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, before the function there is variable new Date() with value a, which returns the present date & time as per the internet network and display in alert box. The document.getElementById("myId")returns the element that has Id"id=myID" in the HTML page. In the <script> block below the function myDate(), we have used toISOString() method, which converts a date object into a string, by using ISO standard from the variable a.  Before displaying the exact output of toISOString() method, first it will display the present time and date in the alert box, after clicking the "Ok" button in the alert box, it will redirect to the HTML page which consists of "Click" button. Onclick of the button "Click" in the HTML code fires the function myDate() in the <script> block at the same time toISOString()method converts a date object into a string using ISO standard and gives the output.


The above output displaying the var a = new Date(); result, click the "ok" button in alert box, and then "Click" button in the HTML page to convert a date object into string, using ISO standard.

 Views: 5934 | Post Order: 134

Write for us

Hosting Recommendations