JavaScript > Date

ToLocaleString() Method in JavaScript

How to convert a date object to a string using locale settings in JavaScript?


By using toLocaleString() method we can convert a date object to a string using locale settings.

<p>Click the below button to convert a date object into string, using Locale settings.</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.toLocaleString(); //* Converts a date object into string using locale settings *//
        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 toLocaleString() method, which converts the date object to a string using locale settings. Before displaying the exact output of toLocaleString() 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 toLocaleString()method converts a date object to a string using locale settings and gives the output.

OUTPUT

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

 Views: 6059 | Post Order: 135



Write for us






Hosting Recommendations