Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
How to convert JSON results into a date using JavaScript?
JSON is a powerful data format to exchange data from server to client and vice versa. Many time JSON data is received in a String format and we need to convert it to a usable JSON object. In this process, it?s an important requirement to convert string data into Date format. In this article, we will learn how to convert JSON results into a Date string using Javascript.
The JSON objects contain the date like this ?
{
name: "John",
time: '/Date(1559072200000)/'
}
And the result will be ?
Wed May 29 2019 01:06:40 GMT+0530 (India Standard Time)
Here are a few approaches to achieve this ?
Using string.replace method
Using Regex
Approach 1: Using String replace( ) Method
The replace method in JavaScript is used to replace a portion of a string with another string. Here are the steps to convert JSON results into a date using the String.replace method.
Replace the first part of the string "/Date(" with an empty string
Replace the last part of the string ")/" with an empty string
Create a new Date object by parsing the number of milliseconds from the JSON string
Now you got the Date and you can use it as a normal javascript date.
Example
In this example we are converting JSON results into a date using the String.replace() method.
Convert JSON results into a date using JavaScript
Click the following button to convert JSON results into a date
Input Data :
/Date(1559072200000)/
Resulting Date:
Approach 2: Using Regex
Here are the following steps to convert JSON results into a date using regex.
Extract the unix timestamp from the JSON date string using regex
Create a new Date object by parsing the number of milliseconds from the JSON string
Now you got the Date and you can use it as a normal javascript date.
Convert JSON results into a date using JavaScript
Click the following button to convert JSON results into a date
Input Data :
/Date(1559072200000)/
Resulting Date:
