I am new in the DataTable Plugin for jquery.
I would like to convert a column date to dd/mm/yyyy but it is returning me in the table this format: Wed Jan 09 2013 00:00:00 GMT+0100 (Hora estándar romance).
$('#tblProceso').dataTable({
"data": dataSet.dataList,
"columns": [
{ "title": "my date", "data": "mydate" }
]
});
Class I am using for it is
Public class DateClass {
Public Property mydate As DateTime
}
this process is called in ajax function and in the response I assign the list of DateClass.
How can I format the column?
What do I need to add?
If you are returning a nullable date time the render function needs to work a little different:
$('#tblProceso').DataTable({
columns: [
{"title": "my date",
"data": "mydate",
"type": "date ",
"render":function (value) {
if (value === null) return "";
var pattern = /Date\(([^)]+)\)/;
var results = pattern.exec(value);
var dt = new Date(parseFloat(results[1]));
return (dt.getMonth() + 1) + "/" + dt.getDate() + "/" + dt.getFullYear();}
}
]};
my approach using Moment.js based at David Sopkpo answer:
$('#tblProceso').DataTable({
columns: [
{"title": "my date",
"data": "mydate",
"type": "date ",
"render":function (value) {
if (value === null) return "";
return moment(value).format('DD/MM/YYYY');
}
}
]};
On method would be like this,
When you create date list at server side, store date in required format (dd/mm/yy). So when you make Ajax call and get list of date, it will came from server by default format you want.
*sorry for my bad English.
if you want to format it with javascript, you need to override of the fnRender function of the column definition. Something like this:
$("#tblProceso").dataTable({
"data": dataSet.dataList,
"aoColumnDefs": [
{
"aTargets": [0], //column index counting from the left
"sType": 'date',
"fnRender": function ( dateObj ) {
var oDate = new Date(dateObj.aData[0]);
result = oDate.getDate()+"/"+(oDate.getMonth()+1)+"/"+oDate.getFullYear();
return "<span>"+result+"</span>";
}
}
],
"columns": [
{ "title": "my date", "data": "mydate" }
]
});
with datatables if you have a column with dates, you will have issues when sorting, so, use this plugin
Related
I am completely new to the topic of APIs and Postman and have the following question:
How can I detect multiple dates in a string and reformat them into a timestamp?
I pulled a JSON format via an API, then converted it to a string via the JSON.stringify function, and then stored it in an environment variable.
It now looks something like this:
[{“date”:“2000-01-01”,“value”:11.8432},{“date”:“2001-01-01”,“value”:112.2348},{“date”:“2002-01-01”,“value”:182.3777},{“date”:“2003-01-01”,“value”:15.0186},{“date”:“2004-01-01”,“value”:131.3781},{“date”:“2005-01-01”,“value”:145.3683}]
Now I’m trying to get this string back into a JSON format but I’d like to add a UNIX time stamp to the date (in milliseconds since January 1, 1970).
So it should look something like this:
[{“date”:946684800000,“value”:11.8432},{“date”:978307200000,“value”:112.2348},{“date”:1009843200000,“value”:182.3777}…
Does anyone know how to solve this within Postman (JavaScript for Postman)?
use moment library and the valueOf() method:
moment = require('moment')
let date = [{ "date": "2000-01-01", "value": 11.8432 }, { "date": "2001-01-01", "value": 112.2348 }, { "date": "2002-01-01", "value": 182.3777 }, { "date": "2003-01-01", "value": 15.0186 }, { "date": "2004-01-01", "value": 131.3781 }, { "date": "2005-01-01", "value": 145.3683 }]
date = date.map((item) => {
item.date = moment(item.date, "YYYY-MM-DD").valueOf()
return item
});
console.log(date)
In react application(nextjs), I want to convert the date format using moment which comes under array of hashes. Data is like,
[
{
"date": "2020-12-22T00:00:00.000Z",
"price": "4365.6384226722"
},
{
"date": "2020-12-23T00:00:00.000Z",
"price": "4084.628672025"
},
{
"date": "2020-12-24T00:00:00.000Z",
"price": "3874.3753251552"
},
...
]
const formatDate = (value) => {
return moment(value).format('HH:MM A DD MM, YYYY')
}
Here, I want to change the date format using formatDate and return it in same data format and which I want to pass it for graph.
Please help to solve this.
You mean this ?
const passedValue = yourArray.map(item => ({
date: formatDate(item.date),
price: item.price
}))
Can anyone help me please .
I am trying to get solution to two problems. First, how to display LocalDate in ajax response. 2nd, iterating over list of Custom objects received in ajax response.
I am passing List of Custom Object and localDate in ajax response and not sure how to display it in UI. date filed is displaying [object object]. Below is my ajax call code.
var table = $("#example").DataTable( {
"bProcessing": true,
"bServerSide": true,
'sDom' : 'T<"clear">lrtip',
"sort": "position",
"sAjaxSource": "springPaginationDataTables.web",
"aoColumns": [
{ "mData": "name" },
{ "mData": "position" },
{ "mData": "office" },
{ "mData": "phone" },
{ "mData": "start_date" },
{ "mData": "salary" },
{ "mData": "dob" },//LocalDate
{ "mData": "addresses" },//list of addresses
],
columnDefs: [
{
targets: [ 6 ],
render: function ( data, type, row ) {
console.log(type);
return data;//process LocalDate here
}
},
{targets: [ 7 ],
render: function ( data, type, row ) {
console.log(type);
return data;//process addresses list here
}
}
]
} );
From MVC Controller I am passing list Of persons into JSON object as below
PersonJsonObject personJsonObject = new PersonJsonObject();
//Set Total display record
personJsonObject.setiTotalDisplayRecords(500);
//Set Total record
personJsonObject.setiTotalRecords(500);
personJsonObject.setAaData(personsList);
Gson gson = new GsonBuilder().setPrettyPrinting().create();
String json2 = gson.toJson(personJsonObject);
return json2;
PersonJsonObject is Jquery Datatable kind of object which holds records track and list of data to be displayed on UI.
Person object has list of address Object. How do iterate over list after getting list say data.getaddresses and store this in variable. I know how do we iterate over list using jsp tags but not sure how to do same in Jquery
Its solved. For LocalDate issue, custom Module needs to be registered. Check this link for details.
Ajax response does not parse LocalDate
For iterating over list, use simple jquery foreach loop
$j.each(data, function (index, value) {
var temp = value.field1+" "+value.field1+" ";//field1 and field2 are fields of custom object
console.log(temp);
return temp;
});
I need to create calendar view with fullcalendar.io. To use calendar I need to create a JSON like this:
var db_data = [
{
"id": 5,
"user_id": 1,
"article_id": 5,
"title": "",
"start": "2016-03-25 15:18:46"
},
{
"id": 4,
"user_id": 1,
"article_id": 5,
"price": 55,
"title": "",
"start": "2016-03-15 15:18:46"
} etc.
I need to put price at calendar from every date from period_start to period_end, but for some prices I have values in database and for other I dont have so I need to use standar price (etc.$50)...
SO I have period_start and period_end and I get some data from database but now I need to create an JSON with objects for dates which are not in database so I create code:
function fulljson (){
var db_data;
$.ajax({
url: "http://localhost:8888/diving/{{$article->id}}",
type: "GET",
async: true,
dataType: "json",
success: function(data) {
db_data = data;
console.log(db_data);
// declare variables
var period_start = new Date('{{ date('Y-m-d', strtotime($article->from)) }}'),
period_end = new Date('{{ date('Y-m-d', strtotime($article->to)) }}'),
current_date = period_start,
array_of_all_dates = [];
// Create a populated array of dates
while (current_date.getTime() <= period_end.getTime()) {
array_of_all_dates.push(current_date);
current_date = new Date(+current_date);
current_date.setDate(current_date.getDate() + 1);
}
// Now loop over the array of populated dates and mutate, so something like
array_of_all_dates = array_of_all_dates.map(function (date) {
var found_in_db = db_data.filter(function (db_data) {
return new Date(db_data.start.replace(" ", "T")).getTime() === date.getTime(); // I need to do this comparison better!
});
if (found_in_db.length > 0) {
return found_in_db[0];
}
var new_object = {
title: '',
start: date,
price: '{{$article->price}}'
};
console.log(new_object);
return new_object;
});
console.log('result'+array_of_all_dates);
drawCalendar(array_of_all_dates);
},
error: function (data) {
console.log(data);
console.log('ERROR');
}
});
};
$(document).ready(function() {
fulljson();
});
function drawCalendar(data) {
$('#calendar').fullCalendar({
header: {
left: 'prev today',
center: 'title',
right: 'next'
},
defaultDate: Date.now(),
eventRender: function(event, element) {
element.find("fc-event-container").remove();
element.find(".fc-content").remove();
element.find(".fc-event").remove();
var new_description =
'<div style="display:inline-flex; float:right;"><div class="col-md-6"style="margin-top:5px";><p class="price">' + event.price + 'e</p></div>';
element.append(new_description);
} ,// allow "more" link when too many events
events: data,
loading: function(bool) {
$('#loading').toggle(bool);
}
}
});
};
And now this code work in Chrome:
But in FireFox I get this:
Please look at 1.2.3. February where I have data from database. You will see the changes.
SO why this code work in Chrome and dont work in Firefox? What is a problem? Is there a better solution to solve this problem?
SO why this code work in Chrome and dont work in Firefox?
Because the date strings provided are not valid and Firefox will transpose those to invalid date when passed to new Date(). Chrome however does parse them but this is not expected behavior cross browser
Send valid ISO strings from server or any format recommended in plugin docs
From fullcalender docs:
When specifying Event Objects for events or eventSources, you may
specify a string in IETF format (ex: "Wed, 18 Oct 2009 13:00:00 EST"),
a string in ISO8601 format (ex: "2009-11-05T13:15:30Z") or a UNIX
timestamp.
I am working on this example from DataTables.net but I have made modification so that it works with my ajax call to my API.
My problem is that my API returns the DateTime values like this...
Created=2015-02-13T00:00:00
I need to be able to convert that to just be just the date without the time for my table (hopefully without changing the API). I have tried everything that I know to try. I am still sort of a beginner at this advanced javascript stuff. I was trying to do just a simple substring but I dont think that is working. Well at least how I was trying anyways.
Thanks for anything help!
DataTables v1.10.5
Jquery v1.11.2 (due to need to support IE8)
Original Problem Code:
$(document).ready(function () {
var table = $('#AllHuddleRecords').DataTable({
"ajax": "../api/huddle/posts",
"columns": [
{
"className": 'details-control',
"orderable": false,
"data": null,
"defaultContent": ''
},
{ "data" : "EmpName" },
{ "data": "Created" },
{ "data" : "PriorityName" },
{ "data" : "TopicName" }
]
});
Thanks to the guidance of cmxl...here is the working code...
var table = $('#AllHuddleRecords').DataTable({
"ajax": "../api/huddle/posts",
"columns": [
{
"className": 'details-control',
"orderable": false,
"data": null,
"defaultContent": ''
},
{ "data" : "EmpName" },
{ "data": "Created" },
{ "data" : "PriorityName" },
{ "data" : "TopicName" }
],
"columnDefs": [
{
"render" : function (data, type, row) {
return new Date(data).toLocaleString();
},
"targets": 2
}
]
});
You can hook in to the column rendering event. See the documentation here:
https://datatables.net/examples/advanced_init/column_render.html
$(document).ready(function() {
$('#example').dataTable( {
"columnDefs": [
{
// The `data` parameter refers to the data for the cell (defined by the
// `data` option, which defaults to the column being worked with, in
// this case `data: 0`.
"render": function ( data, type, row ) {
return data.slice(0, data.indexOf('T'));
},
"targets": 0
},
{ "visible": false, "targets": [ 3 ] }
]
} );
} );
Or if you want to parse the string as a date you can refer to this answer here:
Converting string to date in js
//...
"render": function ( data, type, row ) {
return new Date(data).toString();
}
//...
Here you can look even deeper into the Date object in Javascript:
https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Global_Objects/Date
Is it possible to do some pre-processing on your data before you send it to data tables, for example if you are inserting the following data into your data table, use Date.parse() on each element of your data to convert to the desired format?
var ajaxData = {
"data": [{
"EmpName": "Bob",
"Created": "2015-02-13T00:00:00",
"PriorityName": "Priority1",
"TopicName": "Topic1"
}]
};
$(ajaxData.data).each(function() {
var dateMillis = new Date(this.Created);
this.Created = dateMillis.getMonth() + "/" + dateMillis.getDay() + "/" + dateMillis.getFullYear();
});
Note that if you want to sort on your date column, then the solution may well be to pre-process data and convert dates to milliseconds using Date.parse() and then use render to convert the date to readable format as cmxl suggested. Good luck!