danielpr danielpr - 3 years ago 123
Ajax Question

ajax post datetime to moment js format

HTML

<div class="col-md-12">
<div class="box-body tableForum"></div>
</div>


Js

function getTicketData(ticketId) {

$.ajax({
url: '/api',
type: 'POST',
data: {
module: 'helpdesk/ticket-responses',
method: 'get',
params: [
{
'ticket.id': ticketId
}
]
},
success: function (data) {
var data = JSON.parse(data);
var finalData = data['hydra:member'];

var dataForum = '';
// var postTime = moment().format("D MMM YYYY, kk.mm a"); //I tried this one and
// $(".date-post").html(dataForum.toString()); //This one too

$.each(finalData, function (index, value) {
dataForum += '<div>';
dataForum += '<div class="media-body"><span class="date-post pull-right"><i class="fa-clock-o"></i> posted at '+value.createdAt+'</span>';
dataForum += '</div>';

});
$('.tableForum').html(dataForum);
//console.log(finalData);
}
});
}

function postTicketData(time) {
var params;

params = [
{
name: 'time',
value: createdAt
}
];
}

$.ajax({
url: '/api',
type: 'POST',
data: {
module: 'helpdesk/ticket-responses',
method: 'post',
params: params
},
success: function (data) {
var data = JSON.parse(data);

if(data == 401) {

} else {

var ticketId = ticket.split("/").pop();
getTicketData(ticketId)

}
}
});
}


The default output format from DB is like this:


posted at 2017-07-24T04:26:44+00:00


Basically I want the format like this:


posted at 24-07-2017 16:26


or


posted at 24 Jul 17 16:26


or


posted at 24 Jul 17 04:26 pm


Can someone enlighten me, how to convert to the format I want?

Answer Source

To use the momentjs library, you have to understand the way to use it. When you want to convert your date using moment just use

moment(data_from_db).format("D-MM-YYYY HH:mm")

The above example will produce 24-07-2017 16:26

If you want on different format you only need to change inside the format function. To know more about the format you can read on momentjs website.

For your case, you only need to do something like below

$.each(finalData, function(index, value) {
    dataForum += '<div>';
    dataForum += '<div class="media-body"><span class="date-post pull-right"><i class="fa-clock-o"></i>  posted at '+moment(value.createdAt).format("D-MM-YYYY HH:mm")+'</span>';
    dataForum += '</div>';
});
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download