DataTables properly sort dates in YYYY-MM-DD format only. All other formats they sort as string.
As far as I'm not a fan of adding a library / plugin for every functionality into my projects I tried to solve it by myself.
DataTables are using Date.parse() function to "understand" the date and sort it. (according to https://datatables.net/blog/2014-12-18).
So I decided to override that function and modify it in the way it will "understand" also other date formats.
I added this JS into my code:
let origFunction = Date.parse;
Date.parse = function(str) {
// I want to parse this date format: 27.01.2018
if (str.indexOf('.') > 0) {
str = convertDateToISO(str); // my function translates date into 2018-01-27
}
return origFunction(str);
};
When I test this in the browser console, Date.parse works perfectly fine with my date format, but DataTables keep sorting my european dates as strings.
Any idea what I'm doing wrong? Or is it possible to do it this way?
SOLVED:
After all it looks like really the easiest way is to include "Moment.js" plugin as described here: https://datatables.net/blog/2014-12-18#Operation
But while there was a "no plugin" requirement in my question, I'm accepting answer of #billynoah as a solution too.
You probably want to take a look at orthogonal-data. This allows you to define a custom value for sorting your column. In this case, the most straightforward thing to do is use a timestamp for sorting and then you can display date in any format you want. For data sourced from an object or ajax you can structure your column definition like:
{
data: 'date',
render: {
_: 'display',
sort: 'timestamp'
}
}
For html source you can use the data-order attribute:
<td data-order="1545466488">Sat, Dec 22nd 2018</td>
(Disclaimer / Attribution: This is all more or less straight out of the manual linked above)
Related
I've just finished a video on Lynda.com and can't get the same results the instructor gets using D3. I've created a simpler version of the files in question, and it still doesn't work. The console outputs NaN when I try to retrieve a date.
The CSV, as output from Excel, is:
Date,AM
1995-04-16,3.5
1995-04-17,14.0
1995-04-18,10.8
and the Javascript file contains:
d3.csv("bg_test_date_parsing.csv", function(d) {
return { Date: +d.Date, AM: +d["AM"] };
}, function(data) {
console.log(data[1]);
});
The console in Mozilla gives me:
Object { Date: NaN, AM: 14 }
I can't proceed with any projects because I don't know where to start with importing dates properly. Videos on lynda.com just keep going, and I still don't get how to import and format dates. Also, the CSV originally was formatted 16-04-1995 as an example, outputted from a medical instrument, and I manually typed it into a year-month-day format that apparently D3 will work with. It took me many hours already using Google to get this far, so I'm obviously missing some key understanding.
+d.Date isn't working the way you want. Calling + on 16-04-1995 is resulting in NaN. You can't convert that string to a number like that.
You can convert the string like this, var myDate = new Date('04-16-1995')
Unfortunately, your format is day-month-year, and javascript wants month-day-year.
See this question for what to do about that:
Convert dd-mm-yyyy string to date
Update As #GerardoFurtado notes in his comment, the d3 library has some built in date parsing options that can convert dates in different formats. See the links in his comment.
Using d3, you could convert the string to a Date like this:
var myDate = d3.timeParse("%d-%m-%Y")('16-04-1995')
or, within your loop:
Date: d3.timeParse("%d-%m-%Y")(d.Date)
With libary moment there is option to bring a array of formating options and momentjs use the best match for parsing the input.
For Example:
var date = moment("29-06-1995", ["MM-DD-YYYY", "DD-MM", "DD-MM-YYYY"]);
but what if I want the take the same format that using in parsing for output formating.
var dateText = date.format('selected parse')
How do I know which format moment choose to use?
Currently there is no exposed function for getting the chosen format, however there is a "private" field named _f that contains this information.
var m = moment("29-06-1995", ["MM-DD-YYYY", "DD-MM", "DD-MM-YYYY"]);
m._f // "DD-MM-YYYY"
If you use this, be careful when updating versions of moment. Private fields are not guaranteed to be maintained, and could break between versions.
I've logged this as a feature request for future moment.js functionality.
I have searched for this but couldn't find anyone trying to do what i am doing with jqGrid formatters.
I have a date which I am trying to parse which is not in a jqGrid table, but I am using jqGrid on the site elsewhere and am hoping to parse this date using jqGrid's date parser instead of having to write a seperate method.
I have been messing around with the jGrid object but I need a little help with this.
My date format is ISO8601Long i.e. 2013-11-17T09:00:00
First, I am ensuring the date formats in the formatter are the ones i wish to use:
jQuery.jgrid.formatter.date.srcformat = 'Y-m-d H:i:s';
jQuery.jgrid.formatter.date.newformat = 'j/m/Y g.ia';
Next, I call the jQuery.jgrid.parseDate method in an attempt to parse the date.
jQuery.jgrid.parseDate(0, 0, '2013-11-17T09:00:00');
I am not sure what the first two arguments are, but they look like they might accept a srcformat and newformat. Either way, they don't format as I would expect. There is a fourth too, but this seems to only accept an object.
This leaves me with 2013-11-17GMT09:00:00. While this is a bit easier to understand, it is not in the format I would be expecting. I presume I have missed a step or somehow need to call the formatter after this.
Any pointers would be great.
Thanks,
Dale
The correct usage of parseDate would be the following:
var parsedData = $.jgrid.parseDate("Y-m-d H:i:s", "2013-11-17T09:00:00", "j/m/Y g.ia");
or
var parsedData = $.jgrid.parseDate("ISO8601Long", "2013-11-17T09:00:00", "j/m/Y g.ia");
You can use alternatively Globalize jQuery Plugin.
I am trying to use the date.format and getting an error that format is not a recognized method. I tried to use thesame in new solution, and I'm getting a correct result. Any idea why .format method is not working? These both are in Javascript.
Assuming you are talking about Date type...
It is clear why format method is not working - because there is no such method on Date object.
It is less clear why/when it would work - most likely you are using some script library that modifies Date object to have format method.
But if you are talking about some other type - format function may be present (or added) to any object and it is not possible to suggest anything without code...
I.e. custom object with format function:
var date = { format:function() {alert("Hi");}};
date.format();
I'm trying to convert an HTML table to Excel in Javascript using new ActiveXObject("Excel.application"). Bascially I loop through table cells and insert the value to the corresponding cell in excel:
//for each table cell
oSheet.Cells(x,y).value = cell.innerText;
The problem is that when the cell is in date format of 'dd-mm-yyyy' (e.g. 10-09-2008), excel would read as 'mm-dd-yyyy' (i.e. 09 Oct 2008). I tried to specify NumberFormat like:
oSheet.Cells(x,y).NumberFormat = 'dd-mm-yyyy';
But, it has no effect. It seems that this only affect how excel display the value, not parse. My only solution now is to swap the date like:
var txt = cell.innerText;
if(/^(\d\d)-(\d\d)-\d\d\d\d$/.test(txt)) txt = txt.replace(/^(\d\d)-(\d\d)/,'$2-$1');
But, I'm worrying that it is not generic and a differnt machine setting would fail this.
Is there a way to specific how excel parse the input value?
You can avoid Excel's date parsing by entering the data using its native 'serial' date format. e.g '22nd Dec 08' is 39804 as an Excel serial date. (See here for a good explanation of these)
Then format the cell as you did before.
determine what culture-neutral date formats excel supports
use javascript to parse your date string and output in the an appropriate format
I don't know what formats excel supports but you'd want something like .net's round trip or sortable formats, where it will always be read consistently.
for #2, if you can trust javascript to construct an appropriate date from whatever string you feed it that's fine. if you're not sure about that you might look at a library like datejs where you can be more specific about what you want to happen.
Instead of
oSheet.Cells(x,y).NumberFormat = 'dd-mm-yyyy';
set this:
oSheet.Cells(x,y).NumberFormat = 14;
In Vbscript, we use to resolve this by
If IsDate ( Cell.Value ) Then
Cell.Value = DateValue ( Cell.Value )
End If
Maybe, In java script also you need to play with same approach.
I've tried your code but at end of the process, I re-applied format to the columns containing dates. It works fine, no matter what local language you have configurated yor machine.
Being my excel object defined as 'template', as soon as I got it data filled, I applied (just for example):
template.ActiveSheet.Range("D10:F99").NumberFormat = "dd/MMM/yyyy;#";
best regards