format date US 'MM/DD/YYYY" in DataTables - datatables

https://communitychessclub.com/examine.php DataTables with moment.js is sorting date as a string, not a date. How can I get a sample date of "08/23/2018" to sort properly? That is, I want to sort "mm/dd/yyyy". I simply can't get this to work.
<script src="//cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/moment.js/2.8.4/moment.min.js"></script>
<script src="//cdn.datatables.net/plug-ins/1.10.19/sorting/datetime-moment.js"></script>
<script src="js/dataTables.keepConditions.min.js"></script>
<script>
$.fn.dataTable.moment = function ( format, locale ) {
var types = $.fn.dataTable.ext.type;
// Add type detection
types.detect.unshift( function ( d ) {
return moment( d, format, locale, true ).isValid() ?
'moment-'+format :
null;
} );
// Add sorting method - use an integer for the sorting
types.order[ 'moment-'+format+'-pre' ] = function ( d ) {
return moment( d, format, locale, true ).unix();
};
};
</script>
<script>
$(document).ready(function() {
$.fn.dataTable.moment( 'MM/DD/YYYY' );
$('#cccr').DataTable( {
"ajax": "assets/games.ajax",
"pageLength": 25,
"order": [[ 8, "desc" ]],
"columns": [
{ "data": "Date", "width": "7rem", },
{ "data": "Event" },
{ "data": "ECO" },
{ "data": "White" },
{ "data": "WhiteElo" },
{ "data": "Black" },
{ "data": "BlackElo" },
{ "data": "Result" },
{ "data": "game", visible : false }
]
} );
} );
</script>

Found the culprit. It's in the data - following row:
{
"game": "5533",
"Date": "05/1/2010",
"Event": "RCC FIDE RR #2",
"ECO": "C56",
"White": "Nikolayev, Igor (FM)",
"WhiteElo": "2367",
"Black": "Jones, Aaaron",
"BlackElo": "1966",
"Result": "1-0"
},
You have the format DD to read but the date here is of the format D which makes it a different format which ends up messing the table sorting.
Here's a plunkr including above row as is:
http://plnkr.co/edit/eYRVBr8P4g7Ua4Z7K6JG?p=preview
Fixing the above date format, here's a new plunkr:
http://plnkr.co/edit/zPF9LDZjAAZeqXIJ3XOF?p=preview
And as Alan (DataTables author) suggests in this comment:
At the moment the plug-in only supports a single format in each column. If could probably be modified if you needed to support two or more formats in a single column.
Using a common format for all the dates will help you fix the issue.
Hope this helps.

Related

How to get data from nested array in DataTables?

I used to download data from a json file in this format to my DataTables table:
{
"data": [
["n/a","668","01.11.2021 14:16:20", ... ],
["n/a","670","05.11.2021 23:23:54", ...]
]
}
...
"ajax": "first.json",
columns: [
{ data: 0 },
{ data: 1 }
...
And everythig was ok
But now format of my json was changed:
{
"data": {
"deals": [["n/a", "718", "30/11/2021 21:46:14"], ["", "718", "30/11/2021 21:46:14"], ... ],
"stops": [["07/10/2021 21:48:28", "BTCUSDT"], ["07/10/2021 21:48:28", "BTCUSDT"], ... ]
}
}
And I try to get data like this and get "No data available in table":
...
"ajax": "first.json",
columns: [
{ data: 'deals.0' },
{ data: 'deals.1' }
...
How can I get data from new format of json to my table?
Here is your new JSON structure, provided by the URL:
{
"data": {
"deals": [
["n/a", "718", "30/11/2021 21:46:14"],
["", "718", "30/11/2021 21:46:14"]
],
"stops": [
["07/10/2021 21:48:28", "BTCUSDT"],
["07/10/2021 21:48:28", "BTCUSDT"]
]
}
}
In this structure, the location of the deals data is data.deals. This location points to an array of arrays, which is what DataTables needs (or an array of objects).
(This means the table will only have access to the deals data, since the stops data is in a separate location entirely. But I will assume you only want the deals data to match your original example.)
You therefore need to use the DataTables dataSrc option to tell DataTables where to look in your new JSON:
<table id="example" class="display" style="width:100%"></table>
and:
$(document).ready(function() {
$('#example').DataTable( {
ajax: {
method: "GET",
url: "first.json", // or whatever URL you want to use
dataSrc: "data.deals"
},
"columns": [
{ "title": "Col 1" },
{ "title": "Col 2" },
{ "title": "Col 3" }
]
} );
} );
Because each row of data is an array, you don't need to specify the specific array indexes in your columns - DataTables will iterate over each row array for you.
The result is:

Mongoose saves in UTC but needs to retrieve in different timezones depends on the user timezone

Mongoose saves all dates in UTC format that's OK.
Each user has a specific timezone. It stores the in user's document.
I would like to send any documents to the client with converted dates in the user's timezone.
I know how to format one value, but I'm looking for a solution to avoid transformation one-by-one.
The workaround solution will be a pass-through transform function on the client for each value or recursive modification response.
Any thoughts?
You can do this in aggregation.
Lets say you have this data:
[
{
"_id": {
"$oid": "5f18b5c87f9f9c0fd8322b60"
},
"createdAt": {
"$date": "2020-07-22T21:55:20.575Z"
},
},
{
"_id": {
"$oid": "5f19efac5cfa75483865eaa2"
},
"createdAt": {
"$date": "2020-07-23T20:14:36.108Z"
},
}
]
you can do this:
const timezone = "America/Chicago"
Model.aggregate([
{
$set: {
localTime: {
$dateToString: {
date: "$createdAt",
timezone
}
}
},
}
]);
The result of the aggregation will be:
[
{
"_id": ObjectId("5f18b5c87f9f9c0fd8322b60"),
"createdAt": ISODate("2020-07-22T21:55:20.575Z"),
"localTime": "2020-07-22T16:55:20.575Z"
},
{
"_id": ObjectId("5f19efac5cfa75483865eaa2"),
"createdAt": ISODate("2020-07-23T20:14:36.108Z"),
"localTime": "2020-07-23T15:14:36.108Z"
}
]
Demo example: https://mongoplayground.net/p/7IOGMrC2sf5

How to Add Data to Custom Content for Dynamic Table - Datatable JQuery

I am working with Datatable and trying to add data that coming from ajax.
$(document).ready(function() {
var table = $('#example').DataTable( {
"ajax": "data/arrays.txt",
"columnDefs": [ {
"targets": -1,
"data": null,
"defaultContent": "<button>Click!</button>"
} ]
} );
} );
the code above is working however but I want embed data with defaultContent
Example:
For: {"data": "id"}
"defaultContent":"<a href='address/id'</a>"
Use columns.render instead as shown below:
$(document).ready(function() {
var table = $('#example').DataTable( {
"ajax": "data/arrays.txt",
"columnDefs": [ {
"targets": -1,
"data": null,
"render": function(data, type, full, meta){
if(type === 'display'){
data = 'Click';
}
return data;
}
} ]
} );
} );
If you're using array of objects as you data source use full['id'] instead of full[0] but you need to add column definitions with columns.data option as shown in this example.

How DataTables determine columns type

I have a dynamic table enhanced by jQuery DataTables, which display a custom object similar to this example.
JSON:
{
"data": [
{
"name": "Tiger Nixon",
"position": "System Architect",
"salary": "$320,800",
"start_date": {
"display": "SomeString",
"timestamp": 1303686000
},
"office": "Edinburgh",
"extn": "5421"
},
// ... skipped ...
]}
JavaScript:
$(document).ready(function() {
$('#example').DataTable( {
ajax: "data/orthogonal.txt",
columns: [
{ data: "name" },
{ data: "position" },
{ data: "office" },
{ data: "extn" },
{ data: {
_: "start_date.display",
sort: "start_date.timestamp"
} },
{ data: "salary" }
]
} );
} );
The difference is that I dynamically build the columns configuration, because the columns can be in any order, and others columns can be added or removed from the list. For this example (my case is very similar) the problem is that for some reason the timestamp property is ordered as a String instead of being ordered as a number.
I discovered that after setting the column "type" as "number" the ordering works perfectly. I'm presuming that DataTables is auto detecting the column as "String" for some reason (maybe because the display element is a string).
How does DataTables set the type of the columns, when is not explicitly declared?
Edit 1
I made a sample code to show the problem
http://jsfiddle.net/Teles/agrLjd2n/16/
jQuery DataTables has built-in mechanism for type detection. There are multiple predefined functions for various types with fallback to string data type.
It's also possible to use third-party plug-ins or write your own.
There are multiple ways to specify data type, below are just the few.
SOLUTION 1
Use type option.
$(document).ready(function() {
$('#example').DataTable( {
ajax: "data/orthogonal.txt",
columns: [
{ data: "name" },
{ data: "position" },
{ data: "office" },
{ data: "extn" },
{ data: "start_date.display", type: "date" },
{ data: "salary" }
]
} );
} );
SOLUTION 2
Use returned JSON data for type detection, see columns.data for more information.
$(document).ready(function() {
$('#example').DataTable( {
ajax: "data/orthogonal.txt",
columns: [
{ data: "name" },
{ data: "position" },
{ data: "office" },
{ data: "extn" },
{ data: {
_: "start_date.display",
sort: "start_date.timestamp",
type: "start_date.timestamp",
} },
{ data: "salary" }
]
} );
} );
DataTables always check the "type" property of the column "data" to auto detect the type of the column, if no "type" property is specified it will check the default value "_".
So if you want DataTables to auto detect the type of the column checking the type of your "sort" property you should set the "type" property of data to be equals to your "sort" value
Here is a sample code with different approchs to achieve what I was tryng to do. Thanks #Gyrocode.com and #davidkonrad.
var Cell = function(display, value) {
this.display = display;
this.value = value;
}
$(document).ready(function() {
var cells = [
new Cell("120 (10%)", 120),
new Cell("60 (5%)", 60),
new Cell("30 (2.5%)", 30)
];
$('#example').DataTable( {
data: cells,
columns: [
{
title : "Column NOT OK",
data: {
_: "display",
sort: "value"
}
}, {
type : "num",
title : "Column Ok setting column type",
data: {
_: "display",
sort: "value"
}
}, {
title : "Column Ok changing default value",
data: {
_: "value",
display: "display",
filter: "display"
}
}, {
title : "Column Ok setting data type",
data: {
_: "display",
sort: "value",
type: "value"
}
}, {
type : "num",
title : "Column Not OK",
data: "display"
}
]
} );
} );

dataTables make <tr> clickable to link

I have a dataTables table at http://communitychessclub.com/test.php
My problem is I need to make an entire table row clickable to a link based on a game#. The table lists games and user should click on a row and the actual game loads.
I am unable to understand the previous solutions to this problem. Can somebody please explain this in simple terms?
I previously did this at http://communitychessclub.com/games.php (but that version is too verbose and does disk writes with php echo)
with
echo "<tr onclick=\"location.href='basic.php?game=$game'\" >";
<script>$(document).ready(function() {
$('#cccr').dataTable( {
"ajax": "cccr.json",
"columnDefs": [
{
"targets": [ 0 ],
"visible": false,
}
],
"columns": [
{ "data": "game" },
{ "data": "date" },
{ "data": "event" },
{ "data": "eco" },
{ "data": "white_rating" },
{ "data": "white" },
{ "data": "black_rating" },
{ "data": "black" }
]
} );
} );</script>
"cccr.json" looks like this and is fine:
{
"data": [
{
"game": "5086",
"date": "09/02/2013",
"event": "135th NYS Ch.",
"eco": "B08",
"white": "Jones, Robert",
"white_rating": "2393",
"black": "Spade, Sam",
"black_rating": "2268"
},
...
You can do it this way:
Use fnRowCallback to add a game-id data-attribute to your datatable rows
...
{ "data": "black" }
],
"fnRowCallback": function (nRow, aData, iDisplayIndex, iDisplayIndexFull) {
//var id = aData[0];
var id = aData.game;
$(nRow).attr("data-game-id", id);
return nRow;
}
This will give each row in your table a game id attribute e.g:
<tr class="odd" data-game-id="5086">
Then create a javascript listener for the click event and redirect to the game page passing the game id taken from the tr data-attribute:
$('#cccr tbody').on('click', 'tr', function () {
var id = $(this).data("game-id");
window.location = 'basic.php?game=' + id;
}