datepickerappceleratorappcelerator-titaniumappcelerator-alloy

How to set date of a datepicker in Appcelerator dynamically?


I'm wondering how I can set the selected date of a date picker for ipad/iphone using Appcelerator?

I have a views/dates.xml:

<Window onOpen="setDates">
<Picker id="picker" type="Ti.UI.PICKER_TYPE_DATE"></Picker>
</Window>

In my controllers/dates.js:

function setDates(){
 //Here I want to retrieve my existing picker and set the selected date to something else. 
 //For example: 
 $.picker.setDate(new Date("2017-03-03"));
} 

Unfortunately, the above setDate-function does not work. I can still load the view and the datepicker will be shown, but it will still show the default date of today.


Solution

  • You can set the date in both Alloy XML file or in JS controller file as shown below:

    XML

    <Alloy>
        <Window backgroundColor="blue">
            <Picker id="picker"
              onChange="report"
              type="Ti.UI.PICKER_TYPE_DATE"
              minDate="2014,4,1"
              maxDate="May 1, 2014 12:00:00"
              value="2017-03-03T12:00:00">
            </Picker>
        </Window>
    </Alloy>
    

    .JS file

    $.picker.value = new Date(2017, 3, 3);
    
    // or
    
    $.picker.value = new Date("2017-03-03");
    

    NOTE: There's a difference in setting the default dates in Date Type pickers is that in .JS files, you have to use the JavaScript Date object, while in XML you have to use Moment Parseable date object.