Date comparison to restrict user to select until current date - android

I have a DatePickerDialog in my app and I want the date selected by the user to be restricted until the current date. I am comparing the date selected from the DatePickerDialog with the newDate() and if the selected date is before, I am throwing an error. Please find the code as follows.
DatePickerDialog datePickerDialog = new DatePickerDialog(this,
new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker view, int year,
int monthOfYear, int dayOfMonth) {
Calendar calendar = Calendar.getInstance();
calendar.set(year, monthOfYear, dayOfMonth);
SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MMM-yyyy");
String visitDate = dateFormat.format(calendar.getTime());
try {
Date appointDate = dateFormat.parse(visitDate);
Date currentDate = new Date();
if(appointDate.before(currentDate)){
appointmentDateInputLayout.setError("Date selected is not within range!");
}else{
appointmentDateEditText.setText(visitDate);
appointmentDateInputLayout.setError(null);
}
} catch (ParseException e) {
e.printStackTrace();
}
appointmentDateEditText.setText(visitDate);
}
}, mYear, mMonth, mDay);
datePickerDialog.getDatePicker().setMinDate(System.currentTimeMillis());
datePickerDialog.show();
But when I do this, I am getting an error for selecting today's date also. I want the user to allow the current date. What am I missing here?
Kindly help.

Look, the
Date currentDate = new Date() ;
allocates the date object at the time it was instantiated in the degree of Milliseconds so alternating the allocation and putting date object at the first of the code would give the very early time so the time that you take to choose visitdate would be eventually greater (after) so the number of Milliseconds in the currentDate will be less than number of Milliseconds in the Picked new Date

Try to compare with calendar getTime() method instead of current date.:
If(appointDate.before(calendar.getTime())

Related

Android DatePickerDialog weird TextView

I've discovered something strange:
Let's take a look at the normal DatePickerDialog:
When I add this line which sets the maximum date on yesterday:
datePickerDialog.getDatePicker().setMaxDate(yesterdayCal.getTime().getTime());
It looks like this:
You see the difference? It adds a TextView above the DatePicker. I don't know why.
It looks weird and always shows the same date as selected. I want to remove it? Some ideas?
Full code:
DatePickerDialog datePickerDialog = new DatePickerDialog(this, R.style.DialogTheme, new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
Calendar pickedCal = Calendar.getInstance(Locale.getDefault());
pickedCal.set(year, monthOfYear, dayOfMonth);
setToMidnight(pickedCal);
SimpleDateFormat dateFormat = new SimpleDateFormat("EEE dd.MM.yyyy", Locale.getDefault());
String pickedDate = dateFormat.format(pickedCal.getTime());
MyToast.showLong(LiveSelectActivity.this, getString(R.string.hinweis_nachtragen_gueltig, pickedDate));
startNachtragen(pickedCal.getTime());
}
}, currentCalendar.get(Calendar.YEAR), currentCalendar.get(Calendar.MONTH), currentCalendar.get(Calendar.DAY_OF_MONTH));
/*Setzt das maximale Auswahldatum auf gestern.*/
Calendar yesterdayCal = (Calendar) currentCalendar.clone();
yesterdayCal.add(Calendar.DATE, -1);
datePickerDialog.getDatePicker().setMaxDate(yesterdayCal.getTime().getTime());
datePickerDialog.show();
}
For some reason setting the max date through this line sets the title of the DatePickerDialog
datePickerDialog.getDatePicker().setMaxDate(yesterdayCal.getTime().getTime());
In order to remove the title, use setTitle("")
datePickerDialog.getDatePicker().setMaxDate(yesterdayCal.getTime().getTime());
datePickerDialog.setTitle("");
datePickerDialog.show();

getYear(), getMonth(), getDay are deprecated in Calendar, what to use then?

I want to parse a date from a string and set it in the DatePickerDialog:
try {
myCalendar.setTime(mySimpleFormatter.parse(jsonObj.getString("dob")));
} catch (ParseException e) {
System.out.println("!!!");
}
myEditBox.setText(mySimpleFormatter.format(myCalendar.getTime()));
myDatePickerDialog.getDatePicker().updateDate(myCalendar.getTime().getYear()); // depricated
But the issue is that myCalendar.getTime().getYear(), getMonth(), getDay are deprecated. What should be used then?
Calendar cal = Calendar.getInstance();
cal.setTime(myDate);
int day= cal.get(Calendar.DAY_OF_MONTH);
the Date.getYear(), getMonth() and getDay() are deprecated and specifically ask you to use Calendar.get()
Here is the relevant note from the API documentation
Deprecated. As of JDK version 1.1, replaced by Calendar.get(Calendar.YEAR) - 1900.
http://download.oracle.com/javase/6/docs/api/java/util/Date.html#getYear%28%29
I have used this code :
private void setDateTimeField(){
usereditbirthdateedittext.setOnClickListener(this);
Calendar newCalendar = Calendar.getInstance();
fromDatePickerDialog = new DatePickerDialog(this, new DatePickerDialog.OnDateSetListener() {
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
Calendar newDate = Calendar.getInstance();
newDate.set(year, monthOfYear, dayOfMonth);
SimpleDateFormat dateFormatter = new SimpleDateFormat("dd/MM/yyyy");
usereditbirthdateedittext.setText(dateFormatter.format(newDate.getTime()));
selectedDate = new Date(newDate.getTimeInMillis());
}
},newCalendar.get(Calendar.YEAR), newCalendar.get(Calendar.MONTH), newCalendar.get(Calendar.DAY_OF_MONTH));
}
Kotlin solution :
Calendar.getInstance().get(Calendar.MONTH + 1)
The value returned from get(Calendar.MONTH) is between 0 and 11, with the value 0 representing January, so you need to add +1 to get the current month.
You're actually calling methods on Date, which are deprecated. (myCalendar.getDate() returns a Date object).
On an instance of Calendar, you can use get() and pass it constants to get year, month, date, and more (refer to the linked docs for get()).
I will recommend you to use JodaTime instead as it is more powerful and can solve all of the Date related issues.
Here is the example sample:
DateTimeFormatter fromFormat = DateTimeFormat.forPattern("dd/MM/yyyy"); // String pattern of your DOB from which you want to create DateTime Object
DateTime dob = fromFormat.parseDateTime(jsonObj.getString("dob")); // This will give you DateTime Object
DateTimeFormatter toFormat = DateTimeFormat.forPattern("MMMM dd, yyyy"); // String pattern of your parsed DOB
myEditBox.setText(dob.toString(toFormat)); // April 2, 2016
myDatePickerDialog.getDatePicker().updateDate(dob.getYear());

Android Unable to update correct date when I select December as month from the picker

I am trying to update system time and date. Setting time works fine as i have system permissions in my app and application is signatured as system app also setting date works fine for Months Jan upto Nov, but when i select December as month it is setting month to Jan. this all is cause of i am adding 1 to month but in a case i dont add 1 it creates problem for every month. if I select Dec it is Showing Nov, if I am selecting Jan it works fine , When I select Feb it again selects Jan, If I select March it selects Feb. every time it is setting one month less than the selected one.
here is my code
private TimePickerDialog.OnTimeSetListener timePickerListener = new TimePickerDialog.OnTimeSetListener() {
#Override
public void onTimeSet(TimePicker view, int hourOfDay, int minutes) {
mHour = hourOfDay;
mMinute = minutes;
Calendar c = Calendar.getInstance();
c.set(mYear, mMonth+1, mDay, mHour, mMinute);
Intent intent = new Intent();
intent.setAction(Action);
intent.putExtra("time", c.getTimeInMillis());
getContext().sendBroadcast(intent);
}
};
private DatePickerDialog.OnDateSetListener datePickerListener = new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker arg0, int arg1, int arg2, int arg3) {
mYear = arg1;
mMonth = arg2;
mDay = arg3;
mTimePickerDialog.show();
}
};
at the other end
long when = intent.getLongExtra("time", -1);
if (DEBUG)
Log.i(TAG, "Incoming time: " + when);
if (when / 1000 < Integer.MAX_VALUE) {
SystemClock.setCurrentTimeMillis(when);
}
Time time = new Time();
TvManager tvmng = TvManager.getInstance();
TimerManager timerMgr = null;
if(tvmng!=null)
timerMgr = tvmng.getTimerManager();
time.set(when);
try {
timerMgr.setClkTime(time, true);
} catch (TvCommonException e) {
e.printStackTrace();
}
Please correct the code as mentioned below.
Calendar c = Calendar.getInstance();
c.set(mYear, mMonth, mDay, mHour, mMinute);
remove the +1 you added after the month.
When you set the month in calender than it should be between 0 to 11 when you pass month +1 and your month is 11 then it will be 11+1 =12 and calender consider it as Jan not December.
When you use the date selected for the purpose of showing to user then you have to add month+1 so it will show exact month ,
But when you pass it to calender again for the purpose of storing users selection store it as it is without adding +1 if you added it before then make it month-1 and then add to calender object.
It should work as you expected.
Also look at my solution to over come the issue.
to get formatted date to display user
public static String getDate(Calendar calendar){
String formattedDate;
SimpleDateFormat format = new SimpleDateFormat("MMM dd,yyyy");
formattedDate=format.format(calendar.getTime());
return formattedDate;
}
To set date to calender instance after selecting date from date picker use it like below.
DialogFragment newFragment = new DatePickerDialogFragment() {
#Override
public void onDateSet(DatePicker datePicker, int year, int month, int day) {
super.onDateSet(datePicker, year, month, day);
Calender curDateInstance=Calender.getInstance();
curDateInstance.set(Calendar.YEAR, year);
curDateInstance.set(Calendar.MONTH, month);
curDateInstance.set(Calendar.DAY_OF_MONTH, day);
txtPickUpDate.setText(DateUtils.getDate(curDateInstance));
}
};

How to block only past dates in DatePicker in android

how to block only past date in DatePicker in android?
Am using sample code in that past date and current date getting blocked ,
I need only past date get blocked not current date here is my code
private DatePickerDialog.OnDateSetListener mDateSetListener =
new DatePickerDialog.OnDateSetListener() {
public void onDateSet(DatePicker view, int yearSelected,
int monthOfYear, int dayOfMonth) {
year = yearSelected;
month = monthOfYear;
day = dayOfMonth;
int n_mon = monthOfYear+1;
business_date_et.setText(day+"-"+n_mon+"-"+year);
}
};
private TimePickerDialog.OnTimeSetListener mTimeSetListener =
new TimePickerDialog.OnTimeSetListener() {
public void onTimeSet(TimePicker view, int hourOfDay, int min) {
hour = hourOfDay;
minute = min;
business_time_et.setText(hour+":"+minute);
}
};
protected Dialog onCreateDialog(int id) {
switch (id) {
case DATE_DIALOG_ID:
DatePickerDialog da = new DatePickerDialog(this, mDateSetListener,
mYear, mMonth, mDay);
Calendar c = Calendar.getInstance();
c.add(Calendar.DATE, 1);
Date newDate = c.getTime();
da.getDatePicker().setMinDate(newDate.getTime());
return da;
case TIME_DIALOG_ID:
return new TimePickerDialog(this,
mTimeSetListener, mHour, mMinute, false);
}
return null;
}
Here is a sample code:
DatePicker datePicker = (DatePicker) getView().findViewById(R.id.your_datepicker_id);
final Calendar c = Calendar.getInstance();
c.set(Calendar.HOUR_OF_DAY, c.getMinimum(Calendar.HOUR_OF_DAY));
c.set(Calendar.MINUTE, c.getMinimum(Calendar.MINUTE));
c.set(Calendar.SECOND, c.getMinimum(Calendar.SECOND));
c.set(Calendar.MILLISECOND, c.getMinimum(Calendar.MILLISECOND));
Time now = new Time();
now.setToNow();
datePicker.updateDate(now.year, now.month, now.monthDay);
datePicker.setMinDate(c.getTimeInMillis());
Please note above that you must set MinDate value to the minimum time of the current day and not just the time which is 1 or 2 seconds behind the current time. This takes care of a well know problem of Datepicker in Android.
You can also try this:
da.getDatePicker().setMinDate(newDate.getTime()-(newDate.getTime()%(24*60*60*1000)));
It basically subtracts the current date by the current offset of the day.
Use setMinDate method (minimum API 11):
datePicker.setMinDate(System.currentTimeMillis() - 1000);
For more information regarding your topic :
How to disable dates before today date in DatePickerDialog Android?
How to disable past dates in Android date picker?
You can get date of 1 day after current day with this:
c.add(Calendar.DATE, 1);
So by using
c.add(Calendar.DATE, 1);
You are setting date of tomorrow as Minimum date. So just change that to
c.add(Calendar.DATE, 0);
And it should set today's date as minimum date in datepicker.
Hope it helps.

Android CalendarView: How do I get the date in correct format?

The past few days I've been searching for ways to get a 'readable' date out of my calendarview from android 4.0. I can't manage to find a solution or example that suits my problem. I did get it in miliseconds but not in a date format.
My problem is: I have a calendarview and I want the selected date by the user, shown in logcat in a dateformat yy-mm-dd.
I was used to the datepicker from android 2.2 and I'm not familiar with calendarview and can't find much about it either. Does anyone know a solution for this?
Okay so here is how to do this. When you fire your calendarview activity or a calendarview inside your activity it sets the date to the current date(meaning today). To get this current date just use the Calendar object provided by the java api to get this date example below:
Calendar date = Calendar.getInstance();
// for your date format use
SimpleDateFormat sdf = new SimpleDateFormat("yy-MM-dd");
// set a string to format your current date
String curDate = sdf.format(date.getTime());
// print the date in your log cat
Log.d("CUR_DATE", curDate);
to get a date changed you must do this
CalendarView myCalendar = (CalendarView) findViewById(R.id.myCalenderid);
myCalendar.setOnDateChangeListener(myCalendarListener);
OnDateChangeListener myCalendarListener = new OnDateChangeListener(){
public void onSelectedDayChange(CalendarView view, int year, int month, int day){
// add one because month starts at 0
month = month + 1;
// output to log cat **not sure how to format year to two places here**
String newDate = year+"-"+month+"-"+day;
Log.d("NEW_DATE", newDate);
}
}
kandroidj's answer helps to create date, but not date of correct format.
So to format selected date:
calendarView.setOnDateChangeListener(new CalendarView.OnDateChangeListener() {
#Override
public void onSelectedDayChange(CalendarView view, int year, int month,
int dayOfMonth) {
final SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
Calendar calendar = Calendar.getInstance();
calendar.set(year, month, dayOfMonth);
String sDate = sdf.format(calendar.getTime());
Log.d(TAG, "sDate formatted: " + sDate);
}
});
You should use SimpleDateFormat
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
String selectedDate = sdf.format(new Date(calendar.getDate()));
long date = calenderView.getDate();
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(date);
int Year = calendar.get(Calendar.YEAR);
int Month = calendar.get(Calendar.MONTH);
int Day = calendar.get(Calendar.DAY_OF_MONTH);
//customize According to Your requirement
String finalDate=Year+"/"+Month+"/"+Day;

Categories

Resources