How Do I Convert Any Date objects By JSON Stringify

admin_img Posted By Bajarangi soft , Posted On 08-10-2020

JSON.stringify will convert any date objects into strings. so today we discuss how to convert any date object using java script

How Do I Convert Any Date objects By JSON Stringify

A common use of JSON is to exchange data to/from a web server.

When sending data to a web server, the data has to be a string.

Convert a JavaScript object into a string with JSON.stringify().


Exceptions

Stringify Dates

In JSON, date objects are not allowed. The JSON.stringify() function will convert any dates into strings.

var obj = { name: "John", today: new Date(), city : "New York" };
var myJSON = JSON.stringify(obj);

document.getElementById("demo").innerHTML = myJSON;


Complete Code For Converting  Any Date objects By JSON Stringify

<!DOCTYPE html>
<html>
<head>
    <title>How Do I Convert Any Date objects By JSON Stringify</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
</head>

<body>
<div class="container">
    <br>
    <div class="text-center">
        <h1 id="color" style="color: tomato">How Do I Convert Any Date objects By JSON Stringify</h1>
    </div>
    <br>
    <div class="well">
        <h2 id="demo1"></h2>

    </div>

    <script>
        var obj = { name: "John", today: new Date(), city : "New York" };
        var myJSON = JSON.stringify(obj);

        document.getElementById("demo1").innerHTML = myJSON;

    </script>
</div>
</body>
</html>

 

Related Post