Calculating the number of days between two selected dates in a DateChooser control
Here’s a marginally more interesting sample. I was playing around with the DateChooser (calendar) control and the selectableRange property and figured I’d make a simple application to calculate the differences between two selected dates. The example creates a selectable range of dates from the current date to current date plus 1 year. Users can select any single or range of dates between the start date and end date, and Flex calculates the number of days the user selected using some basic math.
<?xml version="1.0" encoding="utf-8"?> <mx:Application name="DateChooser_selectableRange_test" xmlns:mx="http://www.adobe.com/2006/mxml" layout="vertical" verticalAlign="middle" backgroundColor="white"> <mx:Script> <![CDATA[ import mx.controls.dataGridClasses.DataGridColumn; /* Number of milliseconds in a day. (1000 milliseconds per second * 60 seconds per minute * 60 minutes per hour * 24 hours per day) */ private const MS_PER_DAY:uint = 1000 * 60 * 60 * 24; [Bindable] private var startDate:Date = new Date(); [Bindable] private var endDate:Date = new Date(startDate.fullYear + 1, startDate.month, startDate.date); /* Default label function for the DataGrid. Basically just calls the DateFormatter on the current column's contents. */ private function cellDateFormatter(item:Object, column:DataGridColumn):String { var columnDataField:String = column.dataField; return dateFormatter.format(item[columnDataField]); } /* Custom label function for the last column. Calculates the number of days between the start date and end date. */ private function calculateDays(item:Object, column:DataGridColumn):String { var tempDate:Date = new Date(item.rangeEnd - item.rangeStart); return Math.round((tempDate.time / MS_PER_DAY) + 1).toString(); } ]]> </mx:Script> <mx:DateFormatter id="dateFormatter" formatString="MMM D, YYYY" /> <mx:HBox> <mx:DateChooser id="dateChooser" selectableRange="{{rangeStart:startDate, rangeEnd:endDate}}" allowMultipleSelection="true" /> <mx:DataGrid id="selDates" dataProvider="{dateChooser.selectedRanges}" labelFunction="cellDateFormatter" verticalScrollPolicy="on" height="{dateChooser.height}"> <mx:columns> <mx:DataGridColumn dataField="rangeStart" headerText="Range Start:" /> <mx:DataGridColumn dataField="rangeEnd" headerText="Range End:" /> <mx:DataGridColumn labelFunction="calculateDays" headerText="Number Days:" /> </mx:columns> </mx:DataGrid> </mx:HBox> </mx:Application>
View source enabled in the following example.
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.
-
Add Widgets (Content Sidebar)
This is your Content Sidebar. Edit this content that appears here in the widgets panel by adding or removing widgets in the Content Sidebar area.
26 Responses to Calculating the number of days between two selected dates in a DateChooser control
-
Categories
- Accordion
- AccordionHeader
- ActionScript
- AddChild
- AdvancedDataGrid
- Alert
- alpha
- Animate
- AnimateProperties
- Application
- Application (Spark)
- ArrayCollection
- BarChart
- baseColor
- beta
- beta1
- beta2
- Bitmap
- Bitmap/BitmapData
- BitmapData
- BitmapFill
- BitmapFill (Spark)
- BitmapGraphic
- BitmapImage
- BitmapImage (Spark)
- BitmapImageResizeMode
- Border (Spark)
- BorderContainer (Spark)
- Box
- BuildInfo
- Button
- Button (Spark)
- ButtonBar
- ButtonBar (Spark)
- ByteArray
- Camera
- Charting
- CheckBox
- CheckBox (Spark)
- ClassFactory
- CollectionEvent
- Color
- ColorPicker
- ColorUtil
- ComboBox
- ComboBoxArrowSkin
- Compiler
- Component
- Component (Spark)
- Configuration
- Container
- ContextMenu
- ContextMenuEvent
- ContextMenuItem
- CSSCondition
- CSSSelector
- CSSStyleDeclaration
- CurrencyFormatter
- CursorManager
- Data Binding
- DataGrid
- DataGrid (Spark)
- DataGridColumn
- Date
- DateBase
- DateChooser
- DateField
- DateFormatter
- Debugging
- DefaultComplexItemRenderer
- DefaultTileListEffect
- DropDownList
- DropDownList (Spark)
- DropDownListButtonSkin
- DropDownListSkin
- DropShadowFilter
- E4X
- Effects
- Ellipse
- EmailValidator
- Embed
- Event
- Fade
- FileFilter
- FileReference
- fill
- Filters
- Flash
- Flash Integration
- FlashVars
- Flex 3 SDK
- Flex Builder
- Flex Builder 3
- Flex SDK
- Flex4
- FLVPlayback
- FocusManager
- FontLookup
- Fonts
- Form
- Form (Spark)
- FormHeading (Spark)
- FormItem
- FormItem (Spark)
- Forms
- FTETextField (Spark)
- FullScreen
- FullScreenEvent
- FxAnimateColor
- FxButtonBar
- FxCheckBox
- FXG
- FxHScrollBar
- FxHSlider
- FxList
- FxNumericStepper
- FxRadioButton
- FxRotate3D
- FxScroller
- FxTextArea
- FxTextInput
- FxToggleButton
- FxVScrollBar
- FxVSlider
- getStyleDeclaration()
- GradientEntry
- Graphic (Spark)
- HBox
- HDividedBox
- HGroup (Spark)
- HorizontalLayout
- HorizontalList
- HSBColor (Spark)
- HScrollBar (Spark)
- HSlider
- HSlider (Spark)
- HTML template
- ID3Info
- Image
- Image (Spark)
- ImageSnapshot
- itemRenderer
- JointStyle
- Label
- Label (Spark)
- Legend
- LegendItem
- LigatureLevel
- Line
- LinearGradientStroke
- LineScaleMode
- LinkBar
- LinkButton
- List
- List (Spark)
- Menu
- MenuBar
- Metadata
- MetadataEvent
- Model
- Mouse
- MouseCursor
- MouseEvent
- Move
- Namespace
- NavigatorContent (Spark)
- needsSWF
- NetConnection
- NetStream
- Nightly Builds
- NumberBaseRoundType
- NumberFormatter
- NumberValidator
- NumericCompare
- NumericStepper
- NumericStepper (Spark)
- ObjectProxy
- ObjectUtil
- paddingLeft
- paddingRight
- Panel
- Panel (Spark)
- Parallel
- Path
- PieChart
- PieSeries
- PieSeriesItem
- PopUpAnchor (Spark)
- PopUpButton
- PopUpManager
- ProgrammaticSkin
- ProgressBar
- PropertyChangeEvent
- QName
- RadialGradient
- RadioButton
- RadioButton (Spark)
- RadioButtonGroup
- RadioButtonGroup (Spark)
- Rect
- RegExp
- Regular Expressions
- Repeater
- RichEditableText
- RichText
- RichText (Spark)
- RichTextEditor
- Rotate
- Rotate3D (Spark)
- Scroller (Spark)
- Sequence
- setStyle()
- SimpleText
- SimpleText (Spark)
- skinClass
- Slider
- SliderEvent
- SolidColor
- SolidColorStroke
- Sort
- SortField
- Sound
- SoundEffect
- Spinner (Spark)
- SpriteVisualElement (Spark)
- StageDisplayState
- States
- StringUtil
- StringValidator
- StyleManager
- Styles
- SWFLoader
- SWFObject
- System
- SystemManager
- TabBar
- TabBar (Spark)
- TabNavigator
- TabStopFormat
- Text
- Text Layout Framework (TLF)
- TextArea
- TextArea (Spark)
- TextBox
- TextConverter
- TextEvent
- TextFlow
- TextFlowUtil
- TextFormat
- TextGraphic
- TextInput
- TextInput (Spark)
- TextLayoutFormat
- TextView
- Themes
- TileLayout
- TileList
- TileOrientation
- Timer
- TitleWindow
- TitleWindow (Spark)
- TLF
- ToggleButton (Spark)
- ToggleButtonBar
- ToolTip
- Transition
- Tree
- TruncationOptions
- UIComponent
- UIFTETextField
- Updater
- URLLoader
- URLRequest
- URLUtil
- URLVariables
- ValidationResultEvent
- Validator
- Validators
- VBox
- VDividedBox
- Vector
- VerticalLayout
- VerticalLayout (Spark)
- VGroup (Spark)
- Video
- VideoDisplay
- VideoElement
- VideoElement (Spark)
- VideoEvent
- VideoPlayer (Spark)
- VideoPlayerScrubBar
- ViewStack
- VScrollBar (Spark)
- VSlider
- VSlider (Spark)
- XML
- XMLList
- XMLListCollection
- ZipCodeValidator
- ZipCodeValidatorDomainType
- Zoom
-
Articles
- December 2010
- November 2010
- October 2010
- September 2010
- August 2010
- July 2010
- June 2010
- May 2010
- April 2010
- March 2010
- February 2010
- January 2010
- December 2009
- November 2009
- October 2009
- September 2009
- August 2009
- July 2009
- June 2009
- May 2009
- April 2009
- March 2009
- February 2009
- January 2009
- December 2008
- November 2008
- October 2008
- September 2008
- August 2008
- July 2008
- June 2008
- May 2008
- April 2008
- March 2008
- February 2008
- January 2008
- December 2007
- November 2007
- October 2007
- September 2007
- August 2007
- July 2007
-
Meta


Hmm…this do not work. It only reports 1 day for every selection !
pls press date with shift key…
Odo,
Hold down the Shift key.
Ok thnx :) That works.
how do u select the range here.
Sandeep,
Try clicking on Aug 6th, pressing the Shift key, and then pressing on Aug 22nd.
It should highlight each of the days between the two dates, set the range, and list the number of days as 17.
If you press the Ctrl key, I believe it selects each day individually instead of as a range/series.
How its working?
good!^_^
Bonjour,
How to loop for each day between 2 dates ?
thanks you very much.
Rhoby,
I’m sure there is a better, more efficient way, but maybe this helps:
<?xml version="1.0" encoding="utf-8"?> <mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="vertical" verticalAlign="middle" backgroundColor="white"> <mx:Script> <![CDATA[ import mx.events.CalendarLayoutChangeEvent; import mx.utils.ObjectUtil; private var msInDay:uint = 1000 * 60 * 60 * 24; private function dateChooser_change(evt:CalendarLayoutChangeEvent):void { // textArea.text = ObjectUtil.toString(dateChooser.selectedRanges); textArea.text = ""; if (dateChooser.selectedRanges.length > 0) { var ranges:Object = dateChooser.selectedRanges[0]; var numDays:uint = (ranges.rangeEnd.time - ranges.rangeStart.time) / msInDay; var idx:uint; var retDate:Date; for (idx = 0; idx <= numDays; idx++) { retDate = new Date(ranges.rangeStart.time); retDate.date += idx; textArea.text += retDate.toDateString() + "\n"; } } } ]]> </mx:Script> <mx:DateChooser id="dateChooser" allowMultipleSelection="true" change="dateChooser_change(event);" /> <mx:TextArea id="textArea" editable="false" selectable="false" width="320" height="240" /> </mx:Application>Peter
Hello Petered
First, very big thank you for having responded …
I never thought you were answering me still thank you very much
This site told me everything about Flex and I hope with all my heart that will never end …
This is the solution that I was looking for …
You are the best, MANY THANKS
Hello Petered,
We are working with Flex Builder 3 and We need to select multiple days in a calendar
without pressing the Ctrl or Shift keys. Is it possible?
Thanks
Your example seems to demonstrate the same bug(?) I’m experiencing. When the selectableRange is defined on a DateChooser and allowMultipleSelection=”true”, the selectedRanges do not include the rangeStart. In fact, in your example (at least on my machine), you can’t even select a range that includes the rangeStart date. Anyone else experiencing this?
Is this suppose to display the date selected or find the range. I m confused.
ABC,
Try clicking on Aug 6th, pressing the Shift key, and then pressing on Aug 22nd.
It should highlight each of the days between the two dates, set the range, and list the number of days as 17.
If you press the Ctrl key, I believe it selects each day individually instead of as a range/series.
Peter
Is it possible to show the selected value dynamically in date choosed control
flex_learner,
You could do something like the following, which will set the selected date to July 4, 1980 and then set the DateChooser control’s displayed month and year to that same date:
<?xml version="1.0" encoding="utf-8"?> <mx:Application name="DateChooser_selectedDate_test" xmlns:mx="http://www.adobe.com/2006/mxml" layout="vertical" verticalAlign="middle" backgroundColor="white"> <mx:Date id="dat" fullYear="1980" month="6" date="4" /> <mx:DateChooser id="dateChooser" selectedDate="{dat}" displayedYear="{dat.fullYear}" displayedMonth="{dat.month}" /> </mx:Application>The previous code will give a couple of binding warnings saying:
(a) Data binding will not be able to detect assignments to “fullYear”.
(b) Data binding will not be able to detect assignments to “month”.
The example still works, but if you don’t like those warnings, you could always set the properties using ActionScript instead, as seen in the following example:
<?xml version="1.0" encoding="utf-8"?> <mx:Application name="DateChooser_selectedDate_test" xmlns:mx="http://www.adobe.com/2006/mxml" layout="vertical" verticalAlign="middle" backgroundColor="white"> <mx:Script> <![CDATA[ import mx.events.CalendarLayoutChangeEvent; private function dateChooser_change(evt:CalendarLayoutChangeEvent):void { var selDat:Date = dateChooser.selectedDate; dateChooser.displayedYear = selDat.fullYear; dateChooser.displayedMonth = selDat.month; } ]]> </mx:Script> <mx:DateChooser id="dateChooser" change="dateChooser_change(event);"> <mx:selectedDate> <mx:Date fullYear="1980" month="6" date="4" /> </mx:selectedDate> </mx:DateChooser> <mx:Button id="btn" label="Set new selectedDate" click="dateChooser.selectedDate = new Date(1976, 8, 9);" /> </mx:Application>Peter
Peter,
why the need for Math.round?
return Math.round((tempDate.time / MS_PER_DAY) + 1).toString();
you’d think that item.rangeEnd & item.rangeStart wouldn’t have any time associated with it. but i have seen weird things where the difference in milliseconds between 2 dates is often not perfectly divisible by 1000 * 60 * 60 * 24. Which seems very odd…
I guess this will do
how can i implement the code suggested and return it to a for to use that value
Hi,
i have a problem face from last day.
The problem is that i want to run a countdown Timer. The timer is start from two dates
1. current date (as New Date()).
2. the immediate Monday (as new Date(“Mon Jan 17 2011″))
The problem is with 2nd date.
How i dynamically find the next Monday date ?.
Thanks and welcome for Help.
You should just be able to add 7 days to the second date.
Peter
Thanks Peter.
And if i want to get always UTC time on my PC or another PC in which my app is run, What i do that for this ?
Look in to the various Date getUTC*() type functions:
http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/Date.html#getUTCDate()
Also, there is a static Date.UTC() method which may help.
Peter
Not every day is 1000 * 60 * 60 * 24 milliseconds long.
In EST we have 2 days a year that are 23 and 25 hours long to account for daylight savings time.
hey could you tell me how to find the number of days between two dates using both datefield and datechooser also BindingUtils.bindProperty should be used.