javascript 在 Kendo Grid 中过滤/排序日期时间列

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23141300/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 00:24:33  来源:igfitidea点击:

Filtering/Sorting a DateTime column in Kendo Grid

javascriptkendo-uikendo-grid

提问by Goose

I have a datetime column in my Kendo Grid. The values look like this: 2014-04-11 12:43:41.720

我的 Kendo Grid 中有一个日期时间列。值如下所示:2014-04-11 12:43:41.720

In my grid, I have changed the template to just display them as short dates: 04/11/2014

在我的网格中,我已将模板更改为仅将它们显示为短日期: 04/11/2014

The reason I don't just send data to the columns preformatted is because I want the time to be taken into account for sorting. My problem now is that when filtering, specifically when doing an "equal to" filter, if I select 4/11/2014from the datepicker, it will not show any results because the time is by default 12:00:00.00.

我不只是将数据发送到预先格式化的列的原因是因为我希望将时间考虑在内进行排序。我现在的问题是,在过滤时,特别是在执行“等于”过滤器时,如果我4/11/2014从日期选择器中进行选择,它将不会显示任何结果,因为时间默认为12:00:00.00

Is there anyway I can filter based on the text instead of the value? Or can I send preformatted dates to the grid and have the sort use a different field?

无论如何我可以根据文本而不是值进行过滤吗?或者我可以将预先格式化的日期发送到网格并让排序使用不同的字段吗?

JS snippet of my column:

我的专栏的 JS 片段:

columns: [
    { 
      field: "CREATEDATE",
      title: "Created",
      width: 78,
      template: '#= kendo.toString(kendo.parseDate(CREATEDATE, "yyyy-MM-dd"), "MM/dd/yyyy") #',
      filterable: true,
      attributes: { style: "text-align:center;" }
    }
]

回答by jwatts1980

The Telerik forum has an example of this herefor download.

Telerik 论坛在此处提供了一个可供下载的示例

For convenience I will paste the code that they created. The lower third of the example contains the javascript/jquery needed to hiHyman the built-in Kendo filter operation and allow you to provide your own handling.

为方便起见,我将粘贴他们创建的代码。示例的下三分之一包含劫持内置 Kendo 过滤器操作所需的 javascript/jquery,并允许您提供自己的处理。

Basically, you have to build a new date object using on the portions of the date that you are interested in, ie. day, month, and year.

基本上,您必须使用您感兴趣的日期部分构建一个新的日期对象,即。日、月、年。

<html>
<head>
    <title>Dynamically change date format</title>
    <script src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
    <script src="http://cdn.kendostatic.com/2012.1.515/js/kendo.all.min.js"></script>
    <link href="http://cdn.kendostatic.com/2012.1.515/styles/kendo.common.min.css" rel="stylesheet" />
    <link href="http://cdn.kendostatic.com/2012.1.515/styles/kendo.default.min.css" rel="stylesheet" />
</head>
<body>

    <input id="dropDownList"></input>
    <br />
    <div id="grid"></div>

    <script>
        var sampleData = [
            { name: "John", date: new Date("October 13, 2012 11:13:00")},
            { name: "Lisa", date: new Date("March 18, 2012 07:13:00")},
            { name: "Hyman", date: new Date("September 28, 2011 12:28:43")},
            { name: "Maria", date: new Date("May 28, 2012 11:13:00")},
            { name: "Steven", date: new Date("May 31, 2012 07:13:00")},
            { name: "Bob", date: new Date("September 02, 2012 12:28:43")}
        ];

        var flag = 1;

        function formatDate(date) {
            switch(flag)
            {
                case 1:
                    return kendo.toString(date, "g");
                case 2:
                    return kendo.toString(date, "d");
                case 3:
                    return kendo.toString(date, "Y");
                default:
                    return kendo.toString(date, "F");
            }
        }

        $("#dropDownList").kendoDropDownList({
            dataTextField: "text",
            dataValueField: "value",
            dataSource: [
                { text: "Weekly", value: "1" },
                { text: "Monthly", value: "2" },
                { text: "Yearly", value: "3" }
            ],
            index: 0,
            change: function(e) {
                flag = parseInt(this.value());
                console.log(flag);
                $("#grid").data("kendoGrid").refresh();
            }
        });

        $("#grid").kendoGrid({
            dataSource: {
                data: sampleData,
                schema: {
                    model: {
                        fields: {
                            name: { type: "string" },
                            date: { type: "date" }
                        }
                    }
                }
            },
            columns: [
                { field: "name", title: "Name" },
                { field: "date", title: "Date" , template: "#= formatDate(date) #"}
            ],
            filterable: true
        });

        $(document).ready(function() {
            $("th[data-title=Date]")
                .data("kendoFilterMenu")
                    .form.find("button[type=submit]")
                        .click(function(e) {
                            //gets filter type
                            var filterType = $(this.form).find($("select[data-role=dropdownlist]")).eq(0).val();
                            //if filter is "Is equal to"
                            if(filterType == "eq") {
                                e.preventDefault();
                                //gets the datePicker input date
                                var selectedDate = $(this.form).find($("input[data-role=datepicker]")).eq(0).val();
                                //create a filter
                                $("#grid").data("kendoGrid").dataSource.filter({
                                    field: "date",
                                    //create custom filter operator
                                    operator: function(fieldDate) {

                                        var parsedSelectedDate = kendo.parseDate(selectedDate);
                                        //parse the field date in order to ignore the time
                                        var parsedFieldDate = new Date(fieldDate.getFullYear(),  fieldDate.getMonth(), fieldDate.getDate());
                                        var result = (parsedFieldDate.getTime() == parsedSelectedDate.getTime());

                                        return result;

                                    },
                                    value: selectedDate
                                });
                                //close filter window
                                $("th[data-title=Date]").data("kendoFilterMenu").popup.close();
                            }
                            console.log("filter"); 
                        });
        });
    </script>
</body>
</html>

回答by Goose

A solution for my initial issue of filtering was resolved by jwatts, but I wanted to include another answer for others as I ended up changing my code to address my second question:

jwatts 解决了我最初的过滤问题的解决方案,但我想为其他人提供另一个答案,因为我最终更改了代码以解决我的第二个问题:

"Or can I send preformatted dates to the grid and have the sort use a different field?"

“或者我可以将预先格式化的日期发送到网格并让排序使用不同的字段吗?”

I didend up using the preformatted date in my grid as the column value. Filtering worked well because I didn't have to worry about timestamps. To fix the sorting issue, in my controller (on rebind) I checked DataSourceRequestfor any sort parameters and if the user was sorting the preformatted date column, I switched it instead to use the full datetime column (hidden).

没有最终使用预先格式化的日期在我的网格,该列的值。过滤效果很好,因为我不必担心时间戳。为了解决排序问题,在我的控制器(重新绑定时)中,我检查DataSourceRequest了任何排序参数,如果用户正在对预先格式化的日期列进行排序,我将其切换为使用完整的日期时间列(隐藏)。

if (request.Sorts != null)
{
    foreach (var sort in request.Sorts)
    {
        if (sort.Member.Equals("CREATEDATE_FORMATTED", System.StringComparison.OrdinalIgnoreCase))
        {
            sort.Member = "CREATEDATE";
        }
    }
}

回答by Mideus

I realize this is an old post and seemingly resolved, but I stumbled across this when I ran into this question and found an easier solution for the second part of your question: "can I have the sort use a different field." The KendoUI data grid has a configurationwhich supports this.

我意识到这是一个旧帖子并且似乎已经解决,但是当我遇到这个问题时我偶然发现了这个问题,并为问题的第二部分找到了一个更简单的解决方案:“我可以让排序使用不同的领域。” KendoUI 数据网格具有支持此功能的配置

For example, if I have a column in the grid which shows who last changed a row and the date they changed it (e.g. "John Doe - 7/20/16 10:30 AM", see 'changedByDetail' in the code example) and when the user sorts on the column I only want the datetime aspect sorted, I can achieve this as such:

例如,如果我在网格中有一个列显示谁最后更改了一行以及他们更改它的日期(例如“John Doe - 7/20/16 10:30 AM”,请参阅代码示例中的“changedByDetail”)当用户对列进行排序时,我只希望对日期时间方面进行排序,我可以这样实现:

    gridColumns: [
                { field: 'title', title: 'Title' },
                { field: 'changedByDetail', title: 'Changed'
                    , sortable: {
                        compare: function (a, b, desc){
                            if (a.changedDateTime < b.changedDateTime) {
                                return -1;
                            }
                            else if (a.changedDateTime > b.changedDateTime) {
                                return 1;
                            }
                            return 0;
                        }
                    }
                }
            ]

In this case, my grid datasource contains the datetime in the 'changedDateTime' field in my example. If it didn't, you could likely use a string parse function to strip the datetime from the string, convert to date and do the compare off that.

在这种情况下,我的网格数据源在我的示例中的“changedDateTime”字段中包含日期时间。如果没有,您可能会使用字符串解析函数从字符串中去除日期时间,转换为日期并进行比较。

Hope this helps someone!

希望这对某人有帮助!

回答by Jay

There is another way to show the time with which will is filterable and sortable. I use this in my KendoUI jquery grid and can filter minutes.

还有另一种方法可以显示可过滤和可排序的时间。我在我的 KendoUI jquery 网格中使用它并且可以过滤分钟。

{ field: "CREATEDATE", 
  title: "Created",
  format: "{0:dd/MM/yy hh:mm tt}",
  width: "150px",
  template: "#= kendo.toString(kendo.parseDate(CREATEDATE, 'yyyy-MM-dd hh:mm tt'), 'dd/MM/yyyy hh:mm tt') #" },