Experiencing issues with obtaining the correct data format in JSON when making an AJAX request

After writing a GET API, I am trying to display some records in a data table. However, when retrieving the records in JSON format, the date values are coming in this format: "/Date(1498849454000)/". How can I convert this into "2017-04-11 02:09" format? The actual stored data is in the correct format of "2017-04-11 02:09:17.000". The data type is datetime.

Sample Data

{"data":[{"updtd_date":"\/Date(1498849454000)\/","usecase":"watertank","id":1026,"sms":"Alert: Tank is Full at 01/07/2017 12:33:51 AM ]"},

Code

<script>
            $(document).ready(function () {
                $('#myTable').DataTable({
                    "ajax": {
                        "url": "url",
                        "type": "GET",
                        "datatype": "json"
                    },
                    "columns" : [
                        { "data": "updtd_date", "autoWidth": true },
                        { "data": "usecase", "autoWidth": true },
                        { "data": "id", "autoWidth": true },
                        { "data": "sms", "autoWidth": true }
                        ]
                });
            });
        </script>

        <table id="myTable">
                <thead>
                    <tr>
                        <th>Time</th>
                        <th>Use Case</th>
                        <th>Sl no</th>
                        <th>SMS</th>
                    </tr>
                </thead>
            </table>

Controller

   public ActionResult getSMS()
        {
            using (smartpondEntities dc = new smartpondEntities())
            {
                var data = dc.sms.OrderByDescending(a => a.id).ToList();
                return Json(new { data = data }, JsonRequestBehavior.AllowGet);
            }

        }

Answer №1

To generate a date object, simply input the time in milliseconds as an argument to the Date constructor like this:

var currentDate = new Date(1498849454000);

You can then retrieve the date by using the method currentDate.toDateString()

Answer №2

If the date on your screen appears as Date(1498849454000), it means it is a timestamp.

$time = //input your date after decoding JSON
$time = preg_replace( '/[^0-9]/', '', $time);
$date = date("Y-m-d H:i:s", $time / 1000);

This code snippet will convert the timestamp (divided by 1000 for JS date compatibility) into a human-readable format. I trust this information will be beneficial to you.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Load divs, images, or scripts as they enter the viewport

Upon visiting the website , you may notice that certain elements are loaded only when they enter the viewport. I am interested in learning how to implement this feature and am curious about the specific JavaScript or CSS3 techniques utilized for achieving ...

``Are you looking to unlock the power of vertex and fragment shaders within your three.js projects

Recently, I delved into the world of WebGL by starting to work through a book titled "WebGL: Up and Running". This book utilizes my preferred rendering solution, THREE.js, for creating 3D objects in web browsers. One section of the book caught my attention ...

Breaking down JavaScript arrays into smaller parts can be referred to

Our dataset consists of around 40,000 entries that failed to synchronize with an external system. The external system requires the data to be in the form of subarrays sorted by ID and created date ascending, taken from the main array itself. Each ID can ha ...

Moodle API feedback

Is there a way to extract specific data from the API response by targeting a particular response field? var domainname = 'https://sandbox.moodledemo.net'; var token = '234bc817adf979e93f442946c00aa223'; var fu ...

Is there a way to upload a file and FormData simultaneously without storing the file on the server's disk?

When it comes to uploading files and FormData to a server, I found a method that works well: On the client side, I am using Angular 2 with the following logic: 1. In the component onLoadForeignLightCompanies(event: any) { let fileList: FileList = ev ...

Eliminating single and multiple relationships - Mongoose

My Assignment schema includes references to both Groups and Projects. Assignment == Group [One-One Relationship] Assignment == Projects [One-Many Relationship] Here is my Assignment Schema: var AssignmentSchema = new Schema({ name: String, group ...

Utilize Parse cloud code to navigate and interact with object relationships

I am currently in the process of developing a Parse cloud code function that will produce a similar outcome to a GET request on parse/classes/MyClass, but with the IDs of the relations included. While I have successfully implemented this for a single obje ...

What is the method for creating a random percentage using a dynamic array?

Consider the following dataset: var datas = [{animal:"chicken"}, {animal: "cow"}, {animal: "duck"}]; var after_massage = []; datas.forEach(function(key){ after_massage.push({animal: key.animal}, {percentage: randomPercent(); }) }) I'm current ...

Convert the dataframe into a JSON format in the form of a

Looking for assistance in converting the given dataframe to JSON format using R. I have tried multiple methods but haven't been successful. Any help would be greatly appreciated. Sample code: df <- data.frame(month = c(1, 1, 1, 2, 2, 2), ...

Positioning annotations for negative and positive values on Google Chart

How can I position annotations above for positive values and below for negative ones in a column chart? Another question regarding value and annotation formatting - how can I achieve the same formatting as vAxis for annotations (values above and below col ...

What is your approach to managing errors when using Facebook SDK functions such as FB.getLoginStatus()?

When using functions like FB.getLoginStatus(), there are certain circumstances where console errors may arise. One common error is: Given URL is not allowed by the Application configuration.: One or more of the given... The issue with these errors is t ...

"OBJLoader Three.js r74, bringing vibrantly colored elements to your 3

It's a straightforward process, I import my OBJ model that was exported using 3DS Max. I have the intention of coloring a specific section of the Object. During the animation loop, I implement the following: scene.traverse( function( object ) { ...

Combine JSON array elements, excluding any with undefined index 0

Here's a simple question - I'm looking for an elegant solution to a problem I have (I already have a solution but it's not the best way). The code snippet below shows how I am starting with an empty variable a that is a JSON array. My goal i ...

The Justin TV API: Leveraging the Power of Jquery and JSON

Could someone assist me with using the Justin TV API? I have looked through their documentation and found an example along with returned values (Here's the xml file). However, I am having trouble understanding where it specifies which channel to pull ...

Dynamic cascading dropdowns in Laravel

I am facing an issue with implementing a dependent dropdown feature in my Laravel project. The code I have tried so far is resulting in a 500 internal server error. When I select a value from the first select box (which is populated from the database), the ...

Ways to identify when the socket has been opened by the client?

When utilizing socket.io on the client browser side, is there a way to identify when the socket connection has been successfully opened? I am also interested in monitoring other standard messages such as errors and disconnections. In comparison to the Web ...

Is there a way to make an HTML link target the same as JavaScript window.opener?

Within my project, the main page is where users log in and access the primary tables. Additionally, there are numerous supplementary pages that open in separate windows. Once the login session times out, it is essential to restrict user access to any cont ...

Could not adjust the height of the iframe

One issue I am facing involves a page with an iframe that loads all of the content. My main goal has been to adjust the height of the iframe once it has completely loaded. The following code snippet is executed on the parent: $iFrame.load(function() { ...

Verify that the input value changes onBlur

Is there a way to determine if the value of an input box has changed after blur? $("#username").on('blur', function() { $("#usertext").append("new input<br>"); }) Feel free to check out this jsFiddle example: https://jsfiddle.net/xztpts ...

When the JSON value exceeds a certain length, the JSON format needs to be transformed into a different format dynamically using JavaScript in Node.js

INPUT: The input value appears as follows. { "title" : "new resource", "user" : { "firstName" : "tester", "lastname" : "test" } } OUTPUT: The output is structured in this way { ...