Reformat the date retrieved from Json

When the date is retrieved from the Json data, it is displayed as follows:

2017-09-14T22:11:05.5303556

Is there a way to present it in a more user-friendly format, such as:

09/14/2017 22:11:05

Here is a snippet of the Json data:

[
{
id: 98,
dateCreated: "2017-09-14T22:11:05.5303556"
},
{
id: 99,
dateCreated: "2017-09-14T22:11:05.5615556"
}
]

Furthermore, here is the corresponding JavaScript code:

<script>            
        $.ajax({
            url:'http://mywebsite/api/Response',
            dataType: 'json',               
            success: function(json) {                       
                    myTable = $('#myTable').columns({
                    data:json,
                    schema: [
                        {"header":"ID", "key":"id"},
                        {"header":"Date", "key":"dateCreated"}
                    ],                                                          
                });                     
            }               
        });                     
</script> 

Do you have any suggestions on how to modify the code so that the date is shown in a more user-friendly format? Your assistance is greatly appreciated.

Answer №1

If you're looking to format time and date using JavaScript, you may find it helpful to explore the article on 10 methods to do so.

One way to achieve this is by following a code snippet like the one below for each date:

var example_date = '2017-09-14T22:11:05.5303556';

function formatDate(date) {
var d = new Date(date),
month = d.getMonth(),
date = d.getDate(),
year = d.getFullYear(),
hours = ('0' + d.getHours()).slice(-2),
minutes = ('0' + d.getMinutes()).slice(-2),
seconds = ('0' + d.getSeconds()).slice(-2);

    month++;

    return (month + '/' + date +'/' + year + ' ' + hours + ':' + minutes + ':' + seconds);
}

console.log(formatDate(example_date));

Another option is to utilize .toLocaleTimeString() and .toLocaleDateString() in combination.

If you're open to using a third-party library, consider checking out MomentJS. It simplifies date/time formatting, as shown in the example below:

for (var i in json){
  json[i].dateCreated = moment(json[i].dateCreated).format('MM/DD/YYYY hh/mm/ss');
}

Using the object returned in the code, you would get:

[{"id":98,"dateCreated":"09/14/2017 10/11/05"},{"id":99,"dateCreated":"09/14/2017 10/11/05"}]

Answer №2

Using

new Date(date).toLocaleDateString()
should do the trick

Here's an example:

   $.ajax({
        url: 'http://mywebsite/api/Response',
        dataType: 'json',               
        success: function(json) {
           const data = json.map((obj) => (
              Object.assign(
                 {},
                 obj,
                 { dateCreated: new Date(obj.dateCreated).toLocaleDateString() }
              )
           ));

           myTable = $('#my-table').columns({
              data: data,
              schema: [
                 { "header": "ID", "key": "id" },
                 { "header": "Date", "key": "dateCreated" }
              ],                                                          
           });               
        }               
    });

Hope this information is helpful ^__^

Answer №3

Formatting dates in JavaScript is a common task that has been tackled countless times.

If you're looking for a straightforward solution, check out this answer on Stack Overflow. For a more comprehensive option, I highly recommend using Moment.js.

Here's an example using Moment.js:

moment().format('MMMM Do YYYY, h:mm:ss a');

This will result in: September 15th 2017, 12:57:45 pm

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

generate a listing based on an HTTP query

Here is the code snippet from my controller : @RequestMapping("/allU") public List<Utilisateur> AllU() { return UtilisateurRepo.findAll(); } When I try to access this data in my AngularJS code like this : $scope.list=$http.ge ...

console displaying indentation problems with laravel and vue

I am currently utilizing Vue within Laravel and encountering a multitude of indentation errors in the console. https://i.sstatic.net/sfRec.png Here is an excerpt from my package.json file: "private": true, "scripts": { "clean": "rimraf public/buil ...

NodeAutoComplete: Enhanced Autocompletion for Node.js

I am attempting to utilize autocompletion of a JavaScript file with Node.js and Tern. However, the documentation for Ternjs is incredibly lacking. const tern = require("tern"); const ternServer = new tern.Server({}); const requestDetails = { "qu ...

Invoke a directive's function on a page by utilizing ng-click in AngularJS

Is there a way to call a function from a directive in an HTML page like index using ng-click? Below is the code for my directive: $scope.moreText = function() { $(".showMore").append(lastPart); }; html: <a ng ...

Use vanilla JavaScript to send an AJAX request to a Django view

I'm attempting to make a GET AJAX request to a Django view using vanilla JS. Despite passing is_ajax(), I am having trouble properly retrieving the request object. Below is my JavaScript code. Whether with or without JSON.stringify(data), it does not ...

Dealing with excessively large data for json_encode in PHP

In my Symfony project, I am facing an issue while trying to retrieve database data through AJAX. Specifically, when attempting to json_encode all estimates from our database (over 60k in total), I encounter an out of memory error. Interestingly, if I try t ...

What is the best way to turn off jQuery UI (widget) for a particular element?

Is it possible to disable the Jquery-UI selectmenu widget for a specific element in my project so that it reverts back to its native look and functionality? I have tried various solutions suggested in a Stack Overflow thread about disabling theming for a ...

Can AJAX Delete requests be executed without using jQuery?

Is it possible to use AJAX delete request without using jQuery? My JSON object at localhost:8000 appears like this: { "Students":[{"Name":"Kaushal","Roll_No":30,"Percentage":94.5}, {"Name":"Rohit","Roll_No":31,"Percentage":93.5}, {"Name":"Kumar ...

Arranging Text and Images in HTML/CSS to Ensure Optimal Placement When the Window Size Changes

Hello fellow coders! I've recently started diving into the world of website development and I have a query regarding positioning elements and handling window resizing. Can anyone help me out? I'm trying to center an image, a message, and a passw ...

Is there a way to determine the precise location of the scrollbar within a div element?

Is there a way to obtain the exact position of the scrollbar (scrollY) for a specific div, rather than the entire window? I found an example that seems similar to what I need at the following link: http://plnkr.co/edit/45gKhAIt0DrozS7f0Bz2?p=preview Ho ...

Tips for creating a JSON value without a property name

In order to generate JSON output without property names for DataTables (datatables.net) in the browser, I am faced with the following format requirement: { "aaData": [ [ "Trident", "Internet Explorer 4.0", " ...

Sending a request for the second time may result in data duplication

To upload a file to the server, I use the following code snippet: var fd = new FormData(); fd.append('folder', 'html'); fd.append('permission', 0); fd.append("file", file, file.name); After selecting the file from an input f ...

Having trouble retrieving a specific object from an array using EJS

When re-rendering my form with any errors, I am able to display the errors in a list. However, I would like to access each error individually to display them under the invalid input instead of all at the bottom of the form. Here is what I have tried so f ...

Best practices for making an AJAX call to fetch information from a database

I have a database containing a single table. The table includes columns for Company and Time, among others, with Company and Time being crucial. Users can make appointments by filling out a form. Within the form, there are 2 <select> elements - one ...

What is the best way to convert an IHtmlString to JSON using Json.NET?

I recently converted a field containing raw HTML published via JSON from a string to an IHtmlString. Since the change, the field now appears as an empty object, causing issues with anything consuming that JSON data. // Previously when it was a string... { ...

Steps for modifying an element in an array using Javascript

Currently, I am a beginner in the realm of JavaScript and I am trying to build a todo-style application. So far, I have successfully managed to create, display, and delete items from an array. However, I am facing challenges when it comes to editing these ...

Checking if the current time falls within a specific range while also taking minutes into account

I am currently working on a website for restaurants offering home delivery services. I need to enable or disable the 'Order Now' button based on the designated home delivery timings of each restaurant. For this purpose, I have access to the star ...

Utilize res.render in Node.js to pass multiple data arrays to the view

I am facing an issue with populating two separate selects in my view with different arrays. Can anyone guide me on how to pass two distinct JSON objects using res.render? I have attempted the method below without success. const result1 = {data1: "val ...

When I attempt to return an object from a function and pass the reference to a prop, TypeScript throws an error. However, the error does not occur if the object is directly placed in

Currently, I have the following code block: const getDataForChart = () => { const labels = ['January', 'February', 'March', 'April', 'May', 'June', 'July']; const test = { ...

Methods for utilizing StreamReader for reading a JSON file

Reading a json file from the project folder works fine, but encountering issues when trying to read it from a URL path like try { string filePath = @"http://111.111.111.111/test/test.json"; //this way works // using (StreamReader r = new StreamR ...