How to sort "days ago" formatted date in jqGrid? - date

How can I sort the "days ago" formatted date in jqGrid ? When I sort the grid currently, it can't distinguish between "11 hours ago" and "1 days ago". So "1 day ago" is sorted on the top instead of "11 hours ago".
**Please refer this image of the grid.
My jqGrid has the following code. recommendationData is JSON. Posted column is the date.
$("#tblRecommendationList").jqGrid({
data: recommendationData,
datatype: 'local',
colModel: [
{ name: 'Title', label: 'Title', width: 210, resizable: true },
{ name: 'Channel', label: 'Content Type', width: 120, resizable: true },
{ name: 'StatusNumber', label: 'Status', width: 120, resizable: true,
formatter: GetStatusCode },
{ name: 'Posted', label: 'Posted', width: 120, resizable: true },
{ name: 'RecordId', label: 'RecordId', hidden: true }
],
loadtext: 'Loading...',
loadui: 'block',
emptyDataText: "No Recommendations to display",
shrinkToFit: true,
The date is passed in the following manner.
...
returnList =
(
from i in responseList
select new InQuiraRecommendation
{
StatusNumber = i.statusnumber,
Title = i.title,
Text = i.text,
Posted = GetDaysAgo(i.dateadded),
CaseNumber = i.casenumber,
Priority = i.priority,
Channel = i.channel,
RecordId = i.recordid,
}
).ToList();
}
return returnList;
}
GetDaysAgo( ) changes the "2012-09-13 07:00:00 Etc/GMT" date format to "Days ago" format.

The problem starts with the usage of datatype: 'local' with the data prepared on the server. If you would uses datatype: 'json' the server would be responsible for sorting of the data and you could just returns correctly sorted data to jqGrid.
Another way would be to implement GetDaysAgo method, which converts dates posted back in ISO 8601 format to texts like "11 hours ago" or "1 days ago", on the client side as JavaScript code. So you can use custom formatter (and unformatter) to display the data.
One more option is to define your custom sorttype property for 'Posted' column defined as function. The function could returns for example the number of hours which will be used instead of texts "11 hours ago" or "1 days ago" for sorting by the column.
Here is the first reference to custom sorting and here you will find some code example which could help you. You can simplify the implementation of custom sorting (implementation of sorttype as function) if you would create hidden column with sortable string (ISO 8601 for example). Inside of sorttype function you have access to any other data of the row per the second parameter of sorttype (see here for more information). In the way you can just return ISO 8601 representation of 'Posted' (from hidden column) as the result of sorttype function.

I'd add 'dateadded' to your InQuiraRecommendation class and include that as a hidden field on your grid, then use that as your sort column.

Related

ExtJS: Date field writes the date one day back?

I'm using a 'Ext.form.field.Date' and on CRUD process it writes given date as one day back. I mean if I select 05 June 2018, it writes as 04 June 2018.
I've checked related model and widget itself but nothing seems weird! Why this could be?
Here is model statement and field;
Ext.define('MyApp.FooModel', {
extend: 'Ext.data.Model',
fields: [
{name: 'mydatefld', type: 'date', dateReadFormat: 'c', dateWriteFormat: 'Y-m-d'},
//and implementation
Ext.define('MyApp.BaseDateFld', {
extend: 'Ext.form.field.Date',
xtype: 'basedatefld',
format: 'd.m.Y',
flex: 1,
labelAlign: 'right',
name: 'MyDate Fld',
fieldLabel: 'MyDate Fld',
bind: '{currRec.mydatefld}'
});
Each time saves date as on XHR request payload;
2018-06-05T21:00:00.000Z //But should be 2018-06-06T06:05:00.000Z
Update:
I've tried change dateWriteForm to 'Y-m-d H:i:s' and 'Y-m-d H:i' but still noting changes on payload and keep decrease one day and sets time to 21:00:00
As well tried to change compouter TS to some another as #Alexander adviced but nothing changed.
Update 2:
I've over come the current issue but really a very DRY solution, so not safe!
Below there is insertion method (update method is almost same as this) and formating the related date value on here, thusly became success.
Server accepting the date format for this field as Y-m-d, so I've stated dateWriteFormat on model and submitFormat on datefield as 'Y-m-d' but it keeps write the date value with timestamp.
When I check rec param on method it is as 2018-06-06T21:00:00.000Z(The TZ part shouldn't be here!). And store param changes the givin date one day off as 2018-06-05T21:00:00.000Z.
Still not sure why I can't convert/format through model or field.
Thanks for advices.
recInsertion: function (rec, store) {
store.getProxy().url = store.getProxy().api.create;
rec.data.givindate = Ext.Date.format(rec.data.mydate, 'Y-m-d'); //This is current solution to format date! Which is really not safe and will cause DRY.
Ext.Ajax.request({
url: store.proxy.url,
method: 'POST',
jsonData: JSON.stringify(rec.data),
callback: function (options, success, response) {
Ext.GlobalEvents.fireEvent('showspinner');
if (success) {
Ext.GlobalEvents.fireEvent('refreshList');
}
else
Ext.GlobalEvents.fireEvent('savefailed');
}
});
},

Aurelia converted values and dataTables

I'm using DataTables jQuery plugin in Aurelia component. using column ordering and it works well excluding columns with dates.
Inside this columns I'm using value-convertet to convert isoString value to DD.MM.YYYY date format. Value covreters usage leads to wrong date column ordering, but if I'm not using value-converter everything works well. Unfortunately I didn't find any reason why it doesn't work correctly.
Wrong filtering example: I see rows with date value like 27.05.2010 before 18.05.2017
DataTables init:
$('#searchResultsTable').dataTable({
destroy: true,
searching: false,
paging: false,
orderMulti: false,
order: [[ 2, "desc" ]],
dateFormat: 'DD.MM.YYYY'
});
Date value converter (using moment library):
import * as moment from 'moment';
export class DateFormatValueConverter {
toView(value: Date, format: string): string {
if (value) {
return moment(value).format(format);
}
return null;
}
fromView(value: string, format: string): Date {
var isValid = moment(value, format, true).isValid();
if (value && isValid) {
return moment(value, format).toDate();
}
return null;
}
}
UPDATE:
Ordered with value converter
Orderd without ValueConverter(ordered like it should 2017 year value on the top)
The ordering mechanism of the data table is working correctly - it's your understanding that's off I'm afraid.
When ordering in descending order, any that start with 27. will be at the top, as they're the "biggest". Within all the dates that start with 27, it'll order on the month, biggest first, and then the year.
The order mechanism doesn't realise you're ordering a date so we need to look at the Custom Sorting Plugins;
https://www.datatables.net/plug-ins/sorting/
And specifically the Date-De plugin - as that matches your date format;
https://www.datatables.net/plug-ins/sorting/date-de
An example taken from the above page;
$('#example').dataTable( {
columnDefs: [
{ type: 'de_datetime', targets: 0 },
{ type: 'de_date', targets: 1 }
]
});

How to format json data in miliseconds to Date format in highcharts?

I get array of date from json as 1420185600000,1420531200000,1420617600000,1420704000000,1420790400000,1420876800000. How do I format it to show the correct date in the XAxis labels of the highcharts?
You need to tell highcharts that the xAxis is a date type.
xAxis: {
type: 'datetime'
},
You may need extra formatting if you want the date displayed in some form other than the default. That can be done via the labels.formatter.
Sample code that lets you do what you want (minus what formatting you want your date in):
xAxis: {
categories: [1420185600000,1420531200000,1420617600000,1420704000000,1420790400000,1420876800000],
labels: {
formatter: function () {
return new Date(this.value);
}
}
},
You would then need to determine what parts of your new date string you actually want to show. The sample above doing return Date(this.value) is the kitchen sink approach.
UPDATE: If you want the strings formatted, Highcharts gives you functions to set up the date string. See this fiddle (same as fiddle linked in the comments below with formatter using highcharts): http://jsfiddle.net/CaptainBli/psd3ngsh/13/
xAxis: {
type: "datetime",
categories: xArray,
labels: {
formatter: function () {
return Highcharts.time.dateFormat('%Y-%m-%d %H:%M:%S.%L', new Date(this.value));
}
}
},
arrayOfDatesFromJson = arrayOfDatesFromJson.map(function (element) {
return new Date(element);
});

change the date format in a grid field ExtJS

simple question but I can't figure out how to resolve it.
I'm receiving a date with hour from JSON with this format :
"date_deb":"2013\/12\/28 23:00:00"
Note that the \ are for escaping the / and are not displayed.
I would like to display this dates in this format into my grid :
"28/12/2013 23:00:00"
I've tried this into my fields definition:
{name:'date_deb', type: 'date', dateFormat: 'd-m-Y H:i:s'}
But it's not working, nothing is displayed.
By checking the ExtJS docs, I've seen this :
dateReadFormat
I'm using ExtJS4.2
In your field definition provide the dateFormat as it is returned from the server:
{name:'date_deb', type: 'date', dateFormat: 'Y/m/d H:i:s'}
and then in your column config use ExtJS's built-in dateRenderer with the format you'd like to render your dates with:
renderer: Ext.util.Format.dateRenderer('d/m/Y H:i:s')
You'll only need dateReadFormat and dateWriteFormat if you have a reader (to read data from server) AND a writer (to send modified data back to server) which need different date formats. Otherwise dateFormat will apply as the default format for both.
If the above doesn't work for you, try adding xtype: 'datecolumn' in your grid's 'columns' config.
columns: [{
text : 'date',
dataIndex: 'LoginDateTime',
xtype: 'datecolumn',
format: 'Y-m-d g:i A',
}]
This should work.
use this function to render date for grid
In your column definition define renderer as this
renderer: renderDate
example { dataIndex: 'TaskEndDate', header: 'PlannedEndDate', flex: 1, renderer: renderDate },
function renderDate(value)
{
if (value == '' || value == undefined) {
return '';
}
else {
getDate = new Date(parseInt(value.substr(6)));
}
return Ext.util.Format.date(getDate, 'm-d-Y');
}
In your column config use "formatter".
formatter: 'date("d/m/Y H:i:s")'

What is the proper way to format a UNIX timestamp into a human date in Kendo UI Grid?

Well there seems to be a multitude of similar questions, but none that I can find answering this specific question.. so here goes..
Have a working Kendo UI grid. My datasource is returning a timestamp - here's the JSON response coming back to the code:
You'll notice that the next line is also a date.. returned by MySQL as a standard DateTime format - which I would be happy to use directly. But I've converted the date to a timestamp which I thought would be more universal. (??)
Now I need to do two things - format the timestamp into a readable date and edit the date so it can be saved back to the datasource. But let's tackle formatting first.
My code to display the column currently looks like this:
{ title: "Trial<br>Date",
field: "customer_master_converted_to_customer_date",
format: "{0:d/M/yyyy}",
attributes: {
style: "text-align: center; font-size: 14px;"
},
filterable: true,
headerAttributes: {
style: "font-weight: bold; font-size: 14px;"
}
},
Although I've tried..
toString(customer_master_converted_to_customer_date, "MM/dd/yyyy")
.. and several variations of that - in terms of format string. And yes, I've tried entering:
type: "date",
No matter what I do, I only get the timestamp.
Anyone?
You need to convert the timestamp to a JavaScript date first. Here is a sample implementation:
$("#grid").kendoGrid({
dataSource: {
data: [
{ date: 1371848019 }
],
schema: {
model: {
fields: {
date: {
type: "date",
parse: function(value) {
return new Date(value * 1000);
}
}
}
}
}
}
});
Here is it live: http://jsbin.com/utonil/1/edit
I just had the same problem and i tried this and now works perfectly, good luck.
template :#= kendo.toString(new Date(parseInt(dateOfBirth)), 'yyyy-MM-dd')#"
whre dateOfBirth is the date to format, the result will be like this : 2015-09-11.
good luck.
Thank you #Atanas Korchev, that worked for me, here is what I ended up doing:
// in datasource
schema:{
model: {
fields: {
date: { type: "date",
parse: function(value) {
return new Date(value);
}
}, // … other fields
// in columns
columns: [
{
field: "date",
title: "Date",
type: "date",
format: "{0:dd MMM yyyy}"
},
// ... other columns
]
The easiest way to use the TimeStamp format data from your database for KendoGrid.
https://stackoverflow.com/a/67106362/5671943
<kendo-grid-column class="CreatedAt" field="CreatedAt" title="title"
[width]="120" [headerStyle]="{'background-color': '#36455a','color': '#fff'}"
[style]="{'background-color': '#36455a','color': '#fff'}">
<ng-template kendoGridCellTemplate let-dataItem>
{{dataItem.CreatedAt | date:"yyyy/MM/dd HH:mm:ss"}}
</ng-template>
</kendo-grid-column>