The following example shows how you can filter an MX DataGrid control in Flex using two MX DateField control’s and filtering the ArrayCollection data provider.

<?xml version="1.0" encoding="utf-8"?>
<!-- http://blog.flexexamples.com/2010/02/01/filtering-an-mx-datagrid-control-by-date-range-using-flex/ -->
<mx:Application name="MX_DataGrid_filter_DateField_test"
        xmlns:mx="http://www.adobe.com/2006/mxml"
        layout="vertical"
        verticalAlign="middle"
        backgroundColor="white"
        initialize="init();">
 
    <mx:Script>
        <![CDATA[
            protected const MIN_DATE:Date = new Date(2010, 0, 1);
            protected const MAX_DATE:Date = new Date(2010, 11, 31);
 
            protected function date_labelFunc(item:Object, col:DataGridColumn):String {
                var time:Number = Date.parse(item[col.dataField]);
                return new Date(time).toDateString();
            }
 
            protected function arrColl_filterFunc(item:Object):Boolean {
                var cDate:Number = Date.parse(item.holidayDate);
 
                if (!sDate || !eDate) {
                    return true;
                }
 
                if (sDate.selectedDate && eDate.selectedDate) {
                    return (sDate.selectedDate.time <= cDate) && (eDate.selectedDate.time >= cDate);
                } else if (sDate.selectedDate) {
                    return sDate.selectedDate.time <= cDate;
                } else if (eDate.selectedDate) {
                    return eDate.selectedDate.time >= cDate;
                } else {
                    return true;
                }
            }
 
            protected function init():void {
                sDate.selectedDate = MIN_DATE;
                sDate.selectableRange = {rangeStart:MIN_DATE, rangeEnd:MAX_DATE};
 
                eDate.selectedDate = MAX_DATE;
                eDate.selectableRange = sDate.selectableRange;
            }
        ]]>
    </mx:Script>
 
    <mx:ArrayCollection id="arrColl" filterFunction="arrColl_filterFunc">
        <mx:source>
            <mx:Array>
                <mx:Object holidayName="New Years" holidayDate="2010/1/1" />
                <mx:Object holidayName="Martin Luther King, Jr. Day" holidayDate="2010/1/18" />
 
                <mx:Object holidayName="Groundhog Day" holidayDate="2010/2/2" />
                <mx:Object holidayName="Chinese New Year" holidayDate="2010/2/14" />
                <mx:Object holidayName="Valentine's Day" holidayDate="2010/2/14" />
                <mx:Object holidayName="President's Day" holidayDate="2010/2/15" />
                <mx:Object holidayName="Ash Wednesday" holidayDate="2010/2/17" />
 
                <mx:Object holidayName="Daylight Saving Time starts" holidayDate="2010/3/14" />
                <mx:Object holidayName="St. Patrick's Day" holidayDate="2010/3/17" />
                <mx:Object holidayName="First Day of Spring" holidayDate="2010/3/20" />
 
                <mx:Object holidayName="April Fool's Day" holidayDate="2010/4/1" />
                <mx:Object holidayName="Easter" holidayDate="2010/4/4" />
                <mx:Object holidayName="Administrative Professional's Day" holidayDate="2010/4/21" />
                <mx:Object holidayName="Earth Day" holidayDate="2010/4/22" />
 
                <mx:Object holidayName="Cinco De Mayo" holidayDate="2010/5/5" />
                <mx:Object holidayName="Mothers Day" holidayDate="2010/5/9" />
                <mx:Object holidayName="Armed Forces Day" holidayDate="2010/5/15" />
                <mx:Object holidayName="Memorial Day" holidayDate="2010/5/31" />
 
                <mx:Object holidayName="Flag Day" holidayDate="2010/6/14" />
                <mx:Object holidayName="Father's Day" holidayDate="2010/6/20" />
                <mx:Object holidayName="Summer Begins" holidayDate="2010/6/21" />
 
                <mx:Object holidayName="Independence Day/July 4th" holidayDate="2010/7/4" />
 
                <mx:Object holidayName="Labor Day" holidayDate="2010/9/6" />
                <mx:Object holidayName="Grandparents Day" holidayDate="2010/9/12" />
                <mx:Object holidayName="First Day of Autumn" holidayDate="2010/9/23" />
 
                <mx:Object holidayName="Columbus Day" holidayDate="2010/10/11" />
                <mx:Object holidayName="United Nations Day" holidayDate="2010/10/24" />
                <mx:Object holidayName="Halloween" holidayDate="2010/10/31" />
 
                <mx:Object holidayName="All Saints' Day" holidayDate="2010/11/1" />
                <mx:Object holidayName="Daylight Saving Time Ends" holidayDate="2010/11/7" />
                <mx:Object holidayName="Veteran's Day" holidayDate="2010/11/11" />
                <mx:Object holidayName="Thanksgiving" holidayDate="2010/11/25" />
 
                <mx:Object holidayName="Wright Brothers Day" holidayDate="2010/12/17" />
                <mx:Object holidayName="First Day Winter" holidayDate="2010/12/21" />
                <mx:Object holidayName="Christmas" holidayDate="2010/12/25" />
                <mx:Object holidayName="New Years Eve" holidayDate="2010/12/31" />
            </mx:Array>
        </mx:source>
    </mx:ArrayCollection>
 
    <mx:ApplicationControlBar dock="true">
        <mx:Form>
            <mx:FormItem label="Start date:">
                <mx:DateField id="sDate" change="arrColl.refresh();" />
            </mx:FormItem>
            <mx:FormItem label="End date:">
                <mx:DateField id="eDate" change="arrColl.refresh();" />
            </mx:FormItem>
        </mx:Form>
    </mx:ApplicationControlBar>
 
    <mx:DataGrid id="dGrid" dataProvider="{arrColl}" width="400">
        <mx:columns>
            <mx:DataGridColumn dataField="holidayName" />
            <mx:DataGridColumn dataField="holidayDate" labelFunction="date_labelFunc" />
        </mx:columns>
    </mx:DataGrid>
 
</mx:Application>

View source is enabled in the following example.

 
Tagged with:
 
About The Author

Peter deHaan

Peter deHaan currently works for Adobe on the Flex SDK QA team. While not working on Flex, Flash, and ColdFusion applications, Peter enjoys making up bios and writing in 3rd person. Peter's rarely updated blog can be found at blogs.adobe.com/pdehaan/, actionscriptexamples.com, airexamples.com, and coldfusionexamples.com.

19 Responses to Filtering an MX DataGrid control by date range using Flex

  1. agk says:

    plz send how flex connected to m s access or ms sql server
    send any program

  2. Melody says:

    Can you show an example of this flex component? Thanks!!

  3. polyGeek says:

    Hi Peter, I can’t find any place around here to contact you. I hear that you’re the QE for the Flex 4 text components. I’m having trouble embedding tags. Example would be a span of words that are bold and then make one of those words blue. Is that just a limitation with Flex 4 or am I missing something? I have a blog post about using HTML text in Flex 4 text components. If you have an answer I’d really appreciate it if you commented there. http://polygeek.com/2249_flex_display-html-text-in-the-spark-textarea

    • Peter deHaan says:

      @polyGeek,

      <?xml version="1.0" encoding="utf-8"?>
      <s:Application xmlns:fx="http://ns.adobe.com/mxml/2009" xmlns:s="library://ns.adobe.com/flex/spark">
       
          <fx:Script>
              <![CDATA[
                  import spark.utils.*;
       
                  private function init():void {
                      myTextArea.textFlow = TextFlowUtil.importFromString("The quick brown <span fontWeight='bold'>fox jumps </span><span color='#0000FF' fontWeight='bold'>over</span> the lazy dog.");
                  }
              ]]>
          </fx:Script>
       
          <s:TextArea id="myTextArea" creationComplete="init();" />
       
      </s:Application>

      Peter

  4. Brian says:

    Hello

    What code would I use in the ArrayCollection to get this to work with my PHP data Services?

    Thanks

  5. aku says:

    Thanks for this tutorial…

  6. sabeerdeen says:

    hi..
    Datagrid with date field columns should be sorted by current year (eg: 2010 year records alone should display)
    help me to achieve this..

  7. Adam S says:

    Your site is such a big help!!! I’m working on my first major flex app and I’ve found your site to be a sort of Flex Bible!

    Anyways I’ve got a similar filter that I’m working on in my app, but I’m having a small problem. I’ve got some items that don’t contain dates (so they don’t appear) and I was wondering how I c0uld modify the code so that items not containing a date are not filtered out?

    thanks!

    • Peter deHaan says:

      @Adam S,

      You could try adding something like the following:

      protected function arrColl_filterFunc(item:Object):Boolean {
          var cDate:Number = Date.parse(item.holidayDate);
       
          if (!cDate) {
              return true;
          }
          // ...

      Now if you have dates that cannot be parsed (or there wasn’t a holidayDate in the fx:Object, the item will still display and not be filtered out. You may also need to tweak your date formatter function to return an empty string if the date cannot be parsed/formatted, or else you may get something funny like “Invalid date” in the DataGrid.

      Peter

  8. splatterkep says:

    Hello,

    I realize this is an older thread, but wonder if someone can please point me in the right direction.

    I am trying to use the code on this page to populate a Flex column chart, so that a user can see a default date range on a chart when the page loads, then use date choosers for start and end dates.

    I have the chart working via XML/E4X using HTTPService. I’ve tried adapting the datagrid example here but am not having luck yet.

    Thanks for any and all thoughts,

    sPlat

  9. naidu says:

    how can we include the same date filter in column header renderer?

  10. san says:

    Thanks a lot Peter for this example.
    I would appreciate if anyone in this forum can answer few questions for me.
    1)Is there any way to set the end date to current date(present date). I want users to change the start date but by default always set the end date to current date.

    Looking forward to hear from you.

    Thanks
    San

  11. Anonymous says:

    what i want to do is to click on any perticular cell of calenderand a window should be displayed according to the sclected date. how can i do that which control should i use.?

  12. Samyr MOises says:

    Hi, Peter!
    First of all, thank you so much to share all of this stuff with us!

    I have a kind of a simple question, how can I filter this ArrayCollection when the User try to search holydays typping the text that they want?

    I was thinking about just to save time, because I’m sending a new Remote Object each time that the user whant that….can you help me? tx!

    I’m using Flex 4.5.

    See ya!