Tips for changing date format within Ajax javascript code

I am working with a JavaScript AJAX code:

success:function(res){
                var _html='';
                var json_data=$.parseJSON(res.posts);
$.each(json_data,function (index,data) {
                        _html+='<span class='time'>'+data.fields.time+'</span>';
                    });
                $(".post-wrapper").append(_html);
}

The problem I am facing is that the time format appears as follows:

2021-08-05T22:10:55.255Z

How can I adjust this date format to something like:

2021-08-05 22:10

Answer №1

One way to properly structure the code is to ensure it is formatted within the success function:

let _htmlContent='';
let jsonData=$.parseJSON(response.posts);
$.each(jsonData, function (i, item) { 
    let dateTime = item.time;
    let formattedDate = dateTime.getFullYear() + "-" +
    (dateTime.getMonth() + 1) + "-" + dateTime.getDate() + " " 
    + dateTime.getHours() + ":" + dateTime.getMinutes();
    _htmlContent+='<span class='time'>'+ formattedDate +'</span>';
});

Answer №2

If you're looking to manipulate dates and times, be sure to explore the documentation for Moment.js. This resource can definitely help you out: http://momentjs.com/docs/#/parsing/string+format.

Here's a quick example of how you can use Moment.js in your code:

<span class='time'>'+moment(data.fields.time).format("YYYY-MM-D HH:mm")+'</span>'

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

JavaScript Tab Fade Effect

I have a tab system that utilizes JavaScript to switch tabs. I am trying to implement a fade in and out effect when switching tabs. The current JavaScript simply adds or removes the clicked tab selected by the user. I have managed to partially achieve the ...

Navigate through a list of data in JSON format

After successfully implementing a jQuery AJAX call, I encountered difficulty in parsing the returned value. Working with a MySQL database, I am returning a PHP array() to my jQuery AJAX function using echo json_encode($reservationArray); Upon appending th ...

Retrieving information from a JSON web service can easily be done using just JavaScript and jQuery

I recently downloaded a sample application from the following URL: . I am pleased to report that the part I have implemented is functioning flawlessly: <script src="scripts/jquery-1.3.2.debug.js" type="text/javascript"></script> <script src ...

Prevent floating labels from reverting to their initial position

Issue with Form Labels I am currently in the process of creating a login form that utilizes labels as placeholders. The reason for this choice is because the labels will need to be translated and our JavaScript cannot target the placeholder text or our de ...

Navigating through different tabs in an AngularJS application is made simple and efficient with the help of $

I used the angular-authentication-example to create a login page for my project. After logging in, the homepage should display multiple tabs just like in this example on Plunker. <ul class="nav nav-tabs" ng-controller="TabsCtrl"> <li ng-class= ...

Having trouble updating the sequelize-cli configuration to a dynamic configuration

Encountering an issue while attempting to switch the sequelize-cli configuration to dynamic configuration, following the instructions in the documentation. I have created the .sequelizerc-file in the project's root directory and set up the path to con ...

Error message indicating a problem with the JSON format while trying to read .txt files

I'm currently working on a python script that reads all .txt files in a directory and checks if they meet certain conditions specified in the script. I have numerous .txt files formatted as .json but encounter an error message indicating an invalid .j ...

The asynchronous callbacks or promises executing independently of protractor/webdriver's knowledge

Could a log like this actually exist? 07-<...>.js ... Stacktrace: [31m[31mError: Failed expectation[31m [31m at [object Object].<anonymous> (...06-....js)[31m[31m[22m[39m It seems that something is failing in file -06- while I am processin ...

Guide to dynamically resizing the Monaco editor component using react-monaco-editor

Currently, I am integrating the react-monaco-editor library into a react application for viewing documents. The code snippet below showcases how I have set specific dimensions for height and width: import MonacoEditor from 'react-monaco-editor'; ...

Obtain the parameter of a parent function that runs asynchronously

Here's the code snippet I'm working with: function modify( event, document ) { console.log( "document name", document ); //I need it to be 'file', not 'document'. documents.clients( document, function( clientOfDocument ...

Validating Cognito credentials on the server-side using Node.js

I am currently developing server-side login code for AWS Cognito. My main goal is to verify the existence of a user logging into the identity pool and retrieve the attributes associated with them. With email login, everything is running smoothly using the ...

Variable scope not properly maintained when there is a change in the Firebase promise

I am currently working on developing a controller function to handle signup submissions using Firebase. However, I've encountered an issue where the variables within the scope (controllerAs: $reg) do not seem to update correctly when modified inside a ...

Best practice for displaying image data from PHP for use in Jquery

Struggling with a PHP function called by a jQuery function to display an image on a webpage. The problem seems to be in sending the data back to the jQuery function correctly. Here's how the image is retrieved: if(mysql_query("insert into Personal_P ...

Display a webpage in thumbnail form when hovering the mouse over it

I'm in the process of creating a website that contains numerous sub-pages. I want to display all the links on a single page and when a user hovers over a link, I want to show a thumbnail of the corresponding webpage within a tooltip. I've experi ...

Identifying a Resizable Div that Preserves its Aspect Ratio During Resizing

Below is the HTML code snippet I'm working with: <div id="myid_templates_editor_text_1" class="myid_templates_editor_element myid_templates_editor_text ui-resizable ui-draggable" style="width: 126.79999999999998px; height: 110px; position: absolut ...

Can we access local storage within the middleware of an SSR Nuxt application?

My Nuxt app includes this middleware function: middleware(context) { const token = context.route.query.token; if (!token) { const result = await context.$api.campaignNewShare.createNewShare(); context.redirect({'name': &a ...

Understanding the process of parsing JSON response using JavaScript

I am facing an issue with reading a JSON object in JavaScript. I have received this JSON object as a response and now I need to create a jstree based on it. Here is my JavaScript code: var repoId = $('#frmHdnV').val(); // variable to hold req ...

Tips for positioning two elements side by side on a small screen using the Bootstrap framework

Greetings! As a beginner, I must apologize for the lack of finesse in my code. Currently, I am facing an issue with the positioning of my name (Tristen Roth) and the navbar-toggler-icon on xs viewports. They are appearing on separate lines vertically, lea ...

Execute the assignment of exports.someFunction from within a callback function

My Express route is set up like this: app.get('/api/:type/:id', api.getItemById); The function api.getItemById resides in the api module within routes. However, inside the api module, I need to execute a function that connects to the database a ...

Utilizing TypeScript to Populate an observableArray in KnockoutJS

Is there a way to populate an observableArray in KnockoutJS using TypeScript? My ViewModel is defined as a class. In the absence of TypeScript, I would typically load the data using $.getJSON(); and then map it accordingly. function ViewModel() { var ...