How to use a table column filter with formatted columns? - sapui5

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

Related

Store and Retrieve Date in dd MMM yyyy format in MongoDB model

I have a MongoDB model that contains a Date field whose type is defined as Date.now. Any date is converted to ISO date format. Inside the model the date is defined as :
xDate : {
type: Date.now,
required: true
}
I pass the current Date as :
var d = new Date();
var temp = d.toISOString();
var subStr = temp.substr(10,temp.length - 1);
var curDate = temp.replace(subStr, "T00:00:00.000Z");
console.log(curDate);
However the date is stored as an ISO String inside the MongoDB schema. I try to query it using Mongoose using the following query:
X.
find({
xDate: curDate
})
.exec(function(err, doc) {
var response = {
status : 200,
message : doc
};
if (err) {
console.log('Error');
response.status = 500;
response.message = err;
} else if (!doc) {
console.log("Documents against the date not found in database" ,curDate);
response.status = 404;
response.message = {
"message" : "Documents not found for " + curDate
};
}
res
.status(response.status)
.json(response.message);
});
I keep getting a blank json array inspite of the data being there. Inside the table the xDate is stored as YYYY-MM-DD format.
The date inside mongo is not stores in ISO string. If you save your model as Date.now, it will save a new Date object, not an ISO string. So one easy way of querying is to query by new Date() object.
Also note that your query is hard to be true, since you will have a hard time getting the exactly same date as your data is stored. I think better option for you is using $lt or $gt filters.
New query should look something like:
let currDate = new Date()
// change the date using class methods
X.find({
xDate: {$lt: currDate}
}).exec...

Date Formatting when creating a Model

I'm hard-coding some dates to write back to a model.
E.g.
oEntry.StartDate = "2016-03-28T00:00:00";
This is throwing out an invalid date error on:
oModel.create("/CalendarSet", oEntry, {
success : success,
error : error
});
What is the correct format for the date?
You can just use the Javascript Date element.
oEntry = {
StartDate: new Date(year, month, day, hours, minutes, seconds, milliseconds)
};
oModel.create("/CalendarSet", oEntry, {
success : success,
error : error
});
Source:MDN
If you need it for the sPath in the URL you can use following to get a DateTime String.
getTimestamp: function getTimestamp(oDate){ //TODO: JsDoc
this.oLogger.info("Enterd function Timestamp(oDate)");
return sap.ui.core.format.DateFormat.getDateTimeInstance({pattern : "yyyy-MM-ddTKK:mm:ss"}).format(oDate || new Date());
},
This is what you need:
oEntry = {};
oEntry.StartDate = new Date(); // assuming "StartDate" is corr. fieldname in your service
// also assuming its the only key in your entity
// and its type DateTime
oModel.create("/CalendarSet", oEntry, {
success : success,
error : error
});

Compare date (moment.js) in MongoDB

I want to compare date from MongoDB and my date.
Also i read this and this post and I did not find an answer.
My Code :
today: function() {
var today = moment().format();
return Posts.find({createdAt : { $gte : today}}) // show posts created in "future" , so this function must return nothing
},
createdAt = moment().format();// in MongoDB
As a result this construction doesn't work, but if i compare lie this :
var today = moment().format();
var daystart = moment().startOf('day').format();
if (daystart > today){
console.log ("YES");
}
else if (daystart < today)console.log ("NO");
Return
"NO"
Anybody help ?
EDIT :
today: function() {
var today = moment().toDate();
var daystart = moment().startOf('day').toDate();
// console.log(today + daystart);
return Posts.find({createdAt : { $gt : today}})
},
week: function() {
var today = new Date();
return Posts.find({createdAt : { $lt : today}})
},
month: function() {
var today = new Date();
return Posts.find({createdAt : { $ne : today}})
}
createdAt = new Date();
The .format() method is a display helper function which returns the date string representation based on the passed token argument. To compare the date from MongoDB with the the current date and time, just call moment() with no parameters, without the .format() method and get the native Date object that Moment.js wraps by calling the toDate() method:
today: function() {
var now = moment().toDate();
return Posts.find({createdAt : { $gte : now }});
}
Convert date to MongoDB ISODate format in JavaScript using Moment JS
MongoDB uses ISODate as their primary date type. If you want to insert a date object into a MongoDB collection, you can use the Date() shell method.
You can specify a particular date by passing an ISO-8601 date string with a year within the inclusive range 0 through 9999 to the new Date() constructor or the ISODate() function. These functions accept the following formats:
new Date("<YYYY-mm-dd>") returns the ISODate with the specified date.
new Date("<YYYY-mm-ddTHH:MM:ss>") specifies the datetime in the client’s local timezone and returns the ISODate with the specified datetime in UTC.
new Date("<YYYY-mm-ddTHH:MM:ssZ>") specifies the datetime in UTC and returns the ISODate with the specified datetime in UTC.
new Date() specifies the datetime as milliseconds since the Unix epoch (Jan 1, 1970), and returns the resulting ISODate instance.
If you are writing code in JavaScript and if you want to pass a JavaScript date object and use it with MongoDB client, the first thing you do is convert JavaScript date to MongoDB date format (ISODate). Here’s how you do it.
var today = moment(new Date()).format('YYYY-MM-DD[T00:00:00.000Z]');
console.log("Next day -- " + (reqDate.getDate() + 1))
var d = new Date();
d.setDate(reqDate.getDate() + 1);
var tomorrow = moment(d).format('YYYY-MM-DD[T00:00:00.000Z]');
You can pass today and tomorrow object to MongoDB queries with new Date() shell method.
MongoClient.connect(con, function (err, db) {
if (err) throw err
db.collection('orders').find({ "order_id": store_id, "orderDate": {
"$gte": new Date(today), "$lt": new Date(tomorrow)}
}).toArray(function (err, result) {
console.log(result);
if (err) throw err
res.send(result);
})
})

DOJO Grid Date Text box shows 1970 when user deletes the date

I am new in DOJO grid. I have a grid which have multiple Date Boxes under project Start date for each user. When admin selects one date (e.g. user1 Start Date) and moves on to other field (e.g. description) and comes back and deletes the date (user1 Start Date) it shows 1 Jan 1970. I used formatter and changed the display, but when I submit date then its showing 1 Jan 1970 as selected date. How can I set it for Blank Value? If user deletes the date I want to show Blank value there. How am I suppose to achieve this?
Code I use is as follows
smallLayout.push({
field : editableFieldNames[index],
name : editableColumnNames[index],
sortable : true,
filterable : true,
autoComplete: true,
editable : true,
width : '100px',
styles : 'text-align: left; background:#A3C8EC; color: #000;',
type : dojox.grid.cells.DateTextBox,
constraint: {
datePattern : "dd MMM yyyy",
selector : "date"
},
formatter: formatDate
});
// Formatter to return date in correct format
var formatDate = function (val, rowIdx, cell) {
//dijit.byId('myid').reset();
cell.customClasses.push('noBackgroundClass');
if (val != '0000-00-00' && val != null) {
// If date is comming from database
if (typeof val == 'string') {
return "<div class = 'editableCell'>" + val + "</div>";
} else {
console.log(cell);
if (val.getFullYear == '1970') {
return "<div class = 'editableCell'><div>";
}
return "<div class = 'editableCell'>"
+ val.getDate() + ' '
+ month[val.getMonth() + 1] + ' '
+ val.getFullYear() + "</div>"
;
}
} else {
return "<div class = 'editableCell'><div>";
}
}
Thank You,
Amit

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