Monday, February 27, 2012

BlackBerry DateTimePicker: Selecting a date withing 7 days from now


DateTimePicker can be used to select a particular date. After user selects a date, it can be checked whether the date is within a particular period of time using the after() and before() methods of Calendar.

The DateTimePicker is shown each time the DateTimePicker.doModal()  method is called. A Calendar object of the selected date can be found by calling the DateTimePicker.getDateTime() method.
private String dateText;
Calendar todaysDate = Calendar.getInstance();

public void pickDate()
{
DateTimePicker datePicker = null;

Calendar dateAfter7days = Calendar.getInstance();

long millsAfter7Days = System.currentTimeMillis() + 6*24*60*60*1000 ;
dateAfter7days.setTime(new Date(millsAfter7Days));

datePicker=DateTimePicker.createInstance(todaysDate,"MMMM dd, yyyy",null);
if(datePicker.doModal())
{
if(
datePicker.getDateTime().before(todaysDate)
||
datePicker.getDateTime().after(dateAfter7days)
) {
final String current =
todaysDate.get(Calendar.DAY_OF_MONTH) +
"/" +
( todaysDate.get(Calendar.MONTH)+1 ) +
"/"+
todaysDate.get(Calendar.YEAR);

final String after7days =
dateAfter7days.get(Calendar.DAY_OF_MONTH) +
"/" +
( dateAfter7days.get(Calendar.MONTH)+1 ) +
"/"+
dateAfter7days.get(Calendar.YEAR);

UiApplication.getUiApplication().invokeLater(new Runnable() {
public void run() {
Dialog.alert("Date should be within "+ current +" to " + after7days );
}
});
} else {
Calendar chosenDate = datePicker.getDateTime();
dateText =
chosenDate.get(Calendar.DAY_OF_MONTH) +
"/" +
( chosenDate.get(Calendar.MONTH)+1 ) +
"/"+
chosenDate.get(Calendar.YEAR);
}
}
}