如何使用JavaScript将JSON结果转换为日期
JSON是一种强大的数据格式,用于在服务器和客户端之间交换数据。很多时候,JSON数据以字符串格式接收到,我们需要将其转换为可用的JSON对象。在这个过程中,将字符串数据转换为日期格式是一个重要的需求。在本文中,我们将学习如何使用Javascript将JSON结果转换为日期字符串。
JSON对象包含如下日期格式:
{
name: "John",
time: '/Date(1559072200000)/'
}
结果将是−
Wed May 29 2019 01:06:40 GMT+0530 (India Standard Time)
以下是实现此目标的几种方法 −
- 使用string.replace方法
-
使用正则表达式
方法1:使用String replace()方法
在JavaScript中,replace方法用于替换字符串的一部分为另一个字符串。以下是使用String.replace方法将JSON结果转换为日期的步骤。
- 将字符串的第一部分”/Date(“替换为空字符串
-
将字符串的最后一部分”)/”替换为空字符串
-
通过解析JSON字符串中的毫秒数创建一个新的日期对象
-
现在你已经得到了日期,可以将其用作普通的JavaScript日期。
示例
在这个示例中,我们使用String.replace()方法将JSON结果转换为日期。
<html>
<body>
<h2>Convert JSON results into a date using JavaScript</h2>
<p>Click the following button to convert JSON results into a date</p>
<button id="btn" onclick="convert( )"> Click Here </button> <br>
<h3>Input Data : </h3>
<p id="input"> /Date(1559072200000)/ </p>
<h3> Resulting Date: </h3>
<p id="output"> </p>
<script>
function convert() {
// Store the JSON date string in a variable
var jsonDate = '/Date(1559072200000)/';
// Replace the first part of the string "/Date(" with an empty string
jsonDate = jsonDate.replace("/Date(", " ")
// Replace the last part of the string ")/" with an empty string
jsonDate = jsonDate.replace(")/", " ")
// Create a new Date object by parsing the number of milliseconds from the JSON string
let strDate = new Date(parseInt(jsonDate));
// Get the and output element in the HTML document
let output = document.getElementById("output")
// Set the inner text of the output element to the formatted date
output.innerText = strDate;
}
</script>
</body>
</html>
方法2:使用正则表达式
以下是使用正则表达式将JSON结果转换为日期的步骤。
-
使用正则表达式从JSON日期字符串中提取UNIX时间戳
-
通过解析JSON字符串中的毫秒数创建一个新的日期对象
-
现在你得到了日期,你可以将其作为普通的JavaScript日期来使用
<html>
<body>
<h2>Convert JSON results into a date using JavaScript</h2>
<p>Click the following button to convert JSON results into a date</p>
<button id="btn" onclick="convert( )"> Click Here </button> <br>
<h3>Input Data : </h3>
<p id="input"> /Date(1559072200000)/ </p>
<h3> Resulting Date: </h3>
<p id="output"> </p>
<script>
// Function to convert the JSON date format to a readable date
function convert() {
// The JSON date string in the format '/Date(unixTimestamp)/'
var jsonDate = '/Date(1559072200000)/';
// Extract the Unix timestamp from the JSON date string using regex
jsonDate = jsonDate.match(/\d+/);
// Create a new Date object using the unix timestamp
let strDate = new Date(parseInt(jsonDate));
// Get a reference to the HTML element with the id "output"
let output = document.getElementById("output");
output.innerText = strDate;
}
</script>
</body>
</html>