JavaScript > Date

ToDateString() Method in JavaScript

How to convert the date of a date object into separate readable string in JavaScript?


By using toDateString() method we can convert the date of a date object into separate readable string.

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

<script>
    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.toDateString(); //* Converts the date of a date object into readable string *//
        document.getElementById("myId").innerHTML = r;
    }
</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, 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 toDateString() method, which converts the date of a date object into seperate readable string from the variable a.  Before displaying the exact output of toDateString() 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 toDateString() method converts date of a date object into separate readable string from the new Date() alert and gives the output.

OUTPUT

The above output displaying the var a = new Date(); result and the marked region showing the date of a date object, click the "ok" button in alert box, and then "Click" button in the HTML page to convert the date of a date object into separate readable string.

 Views: 811 | Post Order: 133



Write for us