Search code examples
sapui5

SAPUI5 - How to search formatted date from table


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


Solution

  • 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);
    }