SAPUI5 - How to search formatted date from table - sapui5

I have a date column with format MMM d, yyyy. If user searches "2018", how can I filter it?
XML
<table:Column filterProperty="StartDate" sortProperty="StartDate" width="100px" tooltip="{i18n>ttStartDate}">
<Label text="Start Date"/>
<table:template>
<Text text="{path:'localModel>StartDate',formatter:'.formatter.date'}"/>
</table:template>
</table:Column>
Controller
searchTable: function (evt) {
var oTable = this.getView().byId("ordersTable");
var searchTerm = evt.getParameter("query");
if (searchTerm === "") {
//When clear was pressed on search field
oTable.getBinding("rows").filter(null);
} else {
var filters = [];
var outerFilters = [];
var searchTerms = searchTerm.split(" "); //words separated by space are considered as separate search terms.
for (var k = 0; k < searchTerms.length; k++) {
filters.push(new Filter("OrderType", sap.ui.model.FilterOperator.Contains, searchTerms[k]));
filters.push(new Filter("StartDate", sap.ui.model.FilterOperator.Contains, searchTerms[k]));
outerFilters.push(new Filter(filters));
filters = [];
}
oTable.getBinding("rows").filter(new Filter({
filters: outerFilters,
and: true //Default is OR between filters
}));
}
},
Date received as : StartDate: Sat Mar 23 2019 05:30:00 GMT+0530
Date formatted as: Mar 23,2019
I am aware that 'Contains' works only for Strings but how to make it work for date also

We faced a similar issue and there were 2 solutions,
One on the client side and another on the server side.
Client side:
Use a formatter on that property to parse the date to a string.
Server side:
Ask for another property that is that date as a string.
Looking at your code I can see you are already using a formatter (formatter.date) so we can explore the client side option.
In your formater.date function you can do something like this:
date(yourDateField)
{
let options = { year: 'numeric', month: 'short', day: 'numeric' };
return yourDateField.toLocaleDateString("en-US", options);
}

Related

Free jqGrid restoring date with custom formatter after cancelling inline edit

After inline edit is cancelled, the date column comes back as undefined instead of restoring the original value. Column is defined as following (dates are coming in 1970-01-01 format):
{name:'Release<br>Date',index:'Street_Date', sorttype:"date", width:70,
formatter: function (cellvalue, options, rowObject) {
return cellvalue === ('1970-01-01') ? "" : $.fn.fmatter.call(this, "date", cellvalue, options, rowObject);
},
formatoptions: {newformat:'d M y'},
editable:true,
editoptions: {
size:9,
dataInit: function(el, options) {
$(el).datepicker({
dateFormat: "d M y",
defaultDate: '01 Jan 70',
onSelect: function(dateText, inst) {
}
});
}
},
searchoptions: {
sopt: ['eq','ne','ge','le'],
dataInit: function (elem) {
$(elem).datepicker({ showButtonPanel: true, dateFormat: 'yy-mm-dd' })
}
}
},
The inline edit is setup as following:
ondblClickRow: function (rowid) {
var savedRows = $grid.jqGrid("getGridParam", "savedRow");
if (savedRows.length > 0 && savedRows[0].id !== rowid) {
// cancel editing
$grid.jqGrid("restoreRow", savedRows[0].id);
}
if (savedRows.length === 0) {
$grid.jqGrid("editRow", rowid, editOptions);
}
}
When Grid is loaded, the date shown like 07 Aug 18, entering the inline editing by double click, the date is still 07 Aug 18. After cancelling the edit either by clicking away or clicking Cancel button, date becomes NaN undefined N. After refresh, it comes back correctly though.
How to preserve the correct date after cancelling editing?
Grid behaves correctly with formatter: date
free jqGrid v jqGrid 4.13.5
Maybe the author of free-jqGrid will help better, but I would recommend you to add additional parameter (action='edit') when the formatter is called. Code below:
formatter: function (cellvalue, options, rowObject) {
return cellvalue === ('1970-01-01') ? "" : $.fn.fmatter.call(this, "date", cellvalue, options, rowObject, "edit");
},
Note the last parameter in $.fn.fmatter.call
UPDATE
This is working in my tests.
Since you use a custom date fomatter it is needed the value in savedRows to be unformated in order to be saved correct. In case of default formatter = date this is done automatically.
Below is the code that can be used, suppose you know the index of the field in colModel:
ondblClickRow: function (rowid) {
var savedRows = $grid.jqGrid("getGridParam", "savedRow");
if (savedRows.length > 0 && savedRows[0].id !== rowid) {
// cancel editing
savedRows[0].Release_Date = $.unformat.date.call($grid[0], savedRows[0].Release_Date, $grid[0].p.colModel[1]);
$grid.jqGrid("restoreRow", savedRows[0].id);
}
if (savedRows.length === 0) {
$grid.jqGrid("editRow", rowid, editOptions);
}
}

MongoDB + MeteorJS unable to filter by date?

I'm new to meteorjs and mongodb. I'm having trouble finding a collection of results based on date. First I used the following meteorjs code to confirm there are records.
var application = Applications.findOne({_id:'Y3xCNck6JhABGj9e7'});
var a1 = Applications.find({owner:application.owner}).map(function(app){return {owner:app.owner,createdAt:app.createdAt}});
console.log(application.createdAt); // gives Sun Dec 27 2015 09:19:17 GMT-0500 (Eastern Standard Time)
console.log(a1);
/*
This gives plenty of results. An example is
createdAt: Sun Dec 27 2015 09:16:10 GMT-0500 (Eastern Standard Time)
owner: "s4xcBwWAqSktoQuLA"
Note that the createdAt date for this particular record is before the application.createdAt, which will become relevant in the next set of queries.
*/
Now what I don't understand is why each of these statements give zero results:
var application = Applications.findOne({_id:'Y3xCNck6JhABGj9e7'});
var a2a = Applications.find({createAt:{$lt:application.createdAt}}).map(function(app){return {owner:app.owner,createdAt:app.createdAt}});
var a2b = Applications.find({createAt:{$lt: new Date(application.createdAt)}}).map(function(app){return {owner:app.owner,createdAt:app.createdAt}});
var a2c = Applications.find({createAt:{$lte:application.createdAt}}).map(function(app){return {owner:app.owner,createdAt:app.createdAt}});
var a2d = Applications.find({createAt:{$lte: new Date(application.createdAt)}}).map(function(app){return {owner:app.owner,createdAt:app.createdAt}});
What did I do wrong? In the a1 example, I'm sure there should be records with createdAt being less than the application.createdAt.
additional notes
When I first saved the application, I saved the date as follows:
saveApplication(formVals) {
if (! Meteor.userId()) {
throw new Meteor.Error("not-authorized");
}
formVals['appStatus'] = 1;
formVals['createdAt'] = new Date();
formVals['owner'] = Meteor.userId();
formVals['username'] = Meteor.user().username;
Applications.insert(formVals);
},
Typos:
var a2a = Applications.find({ createAt: { $lt: application.createdAt }})...
should be
var a2a = Applications.find({ createdAt: { $lt: application.createdAt }})...

Sails JS - Waterline ORM - Query Date only, not Time

Looking to query against the date only anyone encountered this?
Sample code:
////MODEL
module.exports = {
attributes: {
date: {
type: 'date',
required: true
}
}
};
////CONTROLLER
var today = moment().toISOString();
var queryObj = { date: today };
var newDay = { date: today };
Day.findOrCreate(queryObj, newDay).exec(function(err, day) {
console.log(day)
});
Obviously this creates a new record on each refresh, as the iso string will change with each passing second.
Thanks for the help!
Instead of querying for a single date, you can query for a date range that includes all of today. First, you'll need to actually create values for that range--I whipped this up using Moment, but there's probably a better way:
var begin = moment(moment().format("YYYY-MM-DD")).toISOString();
var end = moment(moment().format("YYYY-MM-DD")).add(1, 'days').toISOString();
Then you can use query operators to search the range:
var queryObj = {date: {'>=': begin, '<': end}};
Day.findOrCreate(queryObj, newDay).exec(function(err, day) {
console.log(day)
});
As always, be mindful of time zone issues!

Date Filter in sapui5

I have used two date controls to filter a row repeater as,
oF_cell5 = new sap.ui.commons.layout.MatrixLayoutCell({id:"F05",colSpan : 2});
var oCreateFrom = new sap.ui.commons.DatePicker("EV_AE_DATE1",
{width:"150px",placeholder:"Created From",
change:function(oEvent){
oController.onChangeFilterValue(oEvent);}
})
oF_cell51 = new sap.ui.commons.layout.MatrixLayoutCell({id:"F051",colSpan : 2});
var oCreateTill = new sap.ui.commons.DatePicker("EV_AE_DATE2",
{width:"150px",placeholder:"Created Till",
change:function(oEvent){
oController.onChangeFilterValue(oEvent);}
});
Now i have a rowrepeater in which one of the column is CreatedOn date like..,,
new sap.m.HBox({
items:[new sap.ui.commons.TextView({text:"Created on:"}),
new sap.ui.commons.TextView("TV11")
.bindProperty("text",
{
path: "CM_EventList>CREATEDON",
type: new sap.ui.model.type.Date({pattern:"MMM dd, yyyy",
source : {pattern : "dd.MM.yyyy"}})
})]
}),
And in the controller i have written this code as....,,
onInit: function() {
var model = new sap.ui.model.json.JSONModel("eventlist.json");
model.setData();
sap.ui.getCore().setModel(model,"CM_EventList");
},
onChangeCmFilterValue : function(oEvent){
var CM_FDATEVAL = sap.ui.getCore().byId("EV_AE_DATE1").getValue();
var CM_TDATEVAL = sap.ui.getCore().byId("EV_AE_DATE2").getValue();
var CM_Date = new sap.ui.model.Filter('CM_EventList>CREATEDON',
sap.ui.model.FilterOperator.BT,CM_FDATEVAL,CM_TDATEVAL);
var oCM_VBOX1 = sap.ui.getCore().byId("EV_CM_VBOX");
var oCM_RR1 = sap.ui.getCore().byId("EV_AE_ROWREPEATER");
oCM_RR1.bindRows('CM_EventList>/eventlist',oCM_VBOX1,null,[CM_Date]);
},
And the eventlist is my seperate json file which has date values as
{
"eventlist": [
{
"CREATEDON": "10.07.2014",
},
{
"CREATEDON": "10.08.2014",
},
.......
and so on..........
Now if select a date range from my date controls then the row repeater should show the records which are between the range of dates as in my json.
But the filter is not working.
Please Help me on this.
Thanks
Sathish
First of all, use the DatePicker Control for date fields in your view if you aren't using it already.
You can obtain the value of your date picker as a Date object using the method GetDateValue(). You can then use these date objects to create a filter for a datetime field of your data model.
var dateFrom = this.getView().byId("filterDateFrom").getDateValue();
var dateTo = this.getView().byId("filterDateTo").getDateValue();
if (dateFrom != null && dateTo != null) {
filter = new sap.ui.model.Filter(
"CM_EventList>CREATEDON",
sap.ui.model.FilterOperator.BT,
dateFrom,
dateTo
);
}
By the way: Note that both date objects will actually represent the moment at the beginning of the day (0:00:00) while the timestamps in your database will often be some point in time throughout the day. So when you want to search between two dates inclusively, you need to add one day to dateTo:
dateTo.setDate(dateTo.getDate() + 1);
Another problem you might or might not have to deal with are timezones... and of course all the other falsehoods programmers believe about time.
I think you should check the value of the following. The format should be different than your json value "CREATEDON": "10.08.2014".
var CM_FDATEVAL = sap.ui.getCore().byId("EV_AE_DATE1").getValue();
var CM_TDATEVAL = sap.ui.getCore().byId("EV_AE_DATE2").getValue();
Please try create a DatePicker with:
type: new sap.ui.model.type.Date({pattern: ""yyyy-MM-dd""})
Edit: to use Date as filter
var CM_FDATEVAL_DATE = new Date(sap.ui.getCore().byId("EV_AE_DATE1").getValue());
var CM_TDATEVAL_DATE = new Date(sap.ui.getCore().byId("EV_AE_DATE2").getValue());
Regards,
Allen

How to use a table column filter with formatted columns?

I have a JSON model which contains, among others, a few date values which are stored as epoch values:
var oData = [{
string : "SomeValue",
date : 1404172800000
}];
When I load my model, I convert this epoch to a proper Javascript Date object using:
for (var i = 0; i < oData .length; i++) {
var dateLong = oData[i].date;
oData[i].date = new Date(dateLong);
}
In my table, I then render the column using a formatter function:
var oDateColumn = new sap.ui.table.Column({
label: new sap.ui.commons.Label({
text: "A Date"
}),
template: (new sap.ui.commons.TextView({
text : {
parts : [date],
formatter : function(oValue) {
if (oValue != undefined) {
var yyyy = oValue.getFullYear().toString();
var mm = (oValue.getMonth()+1).toString(); // getMonth() is zero-based
var dd = oValue.getDate().toString();
return yyyy + '/' + (mm[1]?mm:"0"+mm[0]) + '/' + (dd[1]?dd:"0"+dd[0]);
} else return "";
}
},
textAlign : sap.ui.core.TextAlign.Right
})),
sortProperty : "date",
filterProperty : "date",
filterOperator : sap.ui.model.FilterOperator.EQ
});
This works ok, and the former epoch is now a date which is nicely rendered as '2014/07/01'
However, the filtering is not on the formatted date but on the original Date object -- if I filter on '2014/07/01' I get no results; if I filter on '1404172800000' I get the filtered results...
I tried using a formatter on the filterProperty but I wasn't able to get this to work.
Does anyone know how I can have users filter on the formatted date?
Using a date type might solve this issue
var dateType = new sap.ui.model.type.Date({
pattern: "yyyy/MM/dd"
});
...
sortProperty : "date",
filterProperty : "date",
filterType: dateType
look at this example for a simple use case on birthday column