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

Tips for transmitting an onChange function from a parent component to a child component in material UI

As a newcomer to react and material UI, I am currently working on developing a dropdown select component. My goal is to pass onChange functions to the component from its parent. Despite following the official documentation closely, I've encountered an ...

Optimal methods for handling Ajax requests in the present day

Recently, I revisited some websites I co-built with a friend and was working on getting them functional again. It's been a while since I've done any AJAX work, and I'm realizing that there aren't many resources available to help trouble ...

AJAX calls experience delays when made in rapid succession

When running an app on my laptop that makes 7 AJAX GET requests simultaneously to a single PHP script, everything works perfectly with all requests returning the desired results. However, after moving the script to a Windows Server running Apache and PHP, ...

load a file with a client-side variable

Is there a way to load a file inside a container while utilizing an argument to fetch data from the database initially? $('#story').load('test.php'); test.php $st = $db->query("select * from users where id = " . $id); ... proce ...

Tips for adjusting the font size of a Chip using Material-UI

I am using a widget called Chip const styles = { root:{ }, chip:{ margin: "2px", padding: "2px" } } const SmartTagChip = (props) =>{ const classes = useStyles(); return( <Chip style={{color:"white&q ...

Unable to successfully reset the validity status to true

After implementing server-side validation using the OnBlur event in a form, I encountered an issue where setting the validity of a field to false does not remove the error messages even after setting it back to true. I expected $setValidity true to clear e ...

Understanding JSON deserialization in Jackson: TypeReference vs TypeFactory.constructCollectionType

If you want to convert a JSON string into a list of a specific class, there are various methods available. You can refer to this StackOverflow thread for more information. Method 1: Check out the details in this documentation link: List<SomeClass> s ...

A webpage designed specifically for handling ajax requests and providing information on how to properly set the content type

Currently in the process of creating a .aspx page to handle ajax requests. How should I go about setting the content type in order for the JSON response to be received correctly by the calling page? Just FYI, I am utilizing jquery for this task. ...

Is Ajax still a popular choice for developing web applications?

Currently, I am developing a comprehensive ajax-based web application and have been investigating various frameworks for SEO optimization and history tracking. During my research, I came across an interesting framework at Although it seems promising, I no ...

Transmit information using JSON format in Angular 8 using FormData

i am struggling with sending data to the server in a specific format: { "name":"kianoush", "userName":"kia9372", "email":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="bcd7d5ddd8ce85...@example.com</a>" } H ...

No data provided in nested parameters for Ajax post request

I am attempting to send an Ajax request to my rails controller using Ajax. $.ajax({ url: '/vulnerabilities/export', type: 'GET', processData: false, data: {export: {ids: this.refs.table.state.selectedRowKeys }} }); When there ...

Error encountered while compiling ./node_modules/@material-ui/core/ButtonBase/ButtonBase.js

I've encountered a frustrating error message: Failed to compile ./node_modules/@material-ui/core/ButtonBase/ButtonBase.js Module not found: Can't resolve '@babel/runtime/helpers/builtin/assertThisInitialized' in 'E:\IT&bsol ...

Is there a way to retrieve the href value from a modal window upon clicking the link?

When clicking on the a href, I am attempting to retrieve a value in my pop-up window. I am using magnificPopup JavaScript Below is the code for my a href tag and I want to fetch the "data-stream" value in the pop-up window. <a class="popup-with-zoom ...

The lack of a defined theme in the makeStyles for @mui/styles sets it apart from @material-ui/core

Struggling to update my material-ui from version 4.11 to version 5 and running into problems with themes. import { createTheme } from '@mui/material/styles'; import { ThemeProvider, StyledEngineProvider, } from '@mui/material/styles&apo ...

Is there a way to manipulate a website's HTML on my local machine using code?

I am currently working on a project to create a program that can scan through a website and censor inappropriate language. While I have been able to manually edit the text using Chrome Dev tools, I am unsure of how to automate this process with code. I ha ...

Struggling to locate the correct setup for .babel and react-hot-loader

I am currently utilizing babel 7. In their documentation, they specify that the new naming convention for plugins should include the @babel/ prefix. The recommended React-hot-loader babelrc configuration is as follows: { "plugins": ["react-hot-loader/ ...

Listen for incoming data from the client in the form of an ArrayBuffer

I have been utilizing the ws library within nodejs to develop a small cursor lobby where players can interact. I have managed to utilize the server to send ArrayBuffers with bit streams to the client and successfully decode them. However, I am encountering ...

Having issues with jQuery AJAX not functioning correctly in PHP environment?

Can someone explain how Ajax and jQuery work together? I'm new to both technologies and I want to use Ajax to delete a row in my index.php file. <head><link rel="stylesheet" type="text/css" href="css/style.css"></head> <h1&g ...

There seems to be an issue with converting JsonArray to JsonObject in Android

This is the code that I have experimented with so far: <?php include('connectdb.php'); $sql = "SELECT salesordercard_code, location_from, location_to, salesmancode FROM salesorderingcard"; $result = mysql_query($sql); ...

Understanding the process of reading long values within a JSON object using JSON.NET

Below is an example of a JSON object: "bookshelf": { "shelfId": 5752814017970176, "shelfName": "Novels", "description": null, "bookOrder": "[5720369633689600, 5631072867975168, 5765651641663488, ...