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();
Related
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())
On one of my app I'm using datepicker class to retrieve data form archive.
I need to set **Max and Min **. On DatePicker.Dialog,
i was able to set **Max to the current time ** however, i counted do for **Min **. if someone to help me i really appreciate it. thanks in advance!
I am looking set setMaxDate = to current year
and setMinDate = two years back from current year(current year -2)
NB: I triad to look if this question was already answered. But, i couldn't get one. all that i see is minData = current timedialog.getDatePicker().setMinDate(new Date().getTime()); which I am not looking for that. i want to set it to different year than the current.
here below part of my code:
// On Clike for Floting button with + signe
#Override
public void onClick(View v) {
switch (v.getId()) {
case imageButtonCalendar:
Calendar c = Calendar.getInstance();
final int[] mYear = {c.get(Calendar.YEAR)};
final int[] mMonth = {c.get(Calendar.MONTH)};
final int[] mDay = {c.get(Calendar.DAY_OF_MONTH)};
DatePickerDialog.OnDateSetListener pDateSetListener = new DatePickerDialog.OnDateSetListener() {
public void onDateSet(DatePicker view, int year,
int monthOfYear, int dayOfMonth) {
mYear[0] = year;
mMonth[0] = monthOfYear;
mDay[0] = dayOfMonth;
et.setText(new StringBuilder()
// to set date in editext
.append(mDay[0]).append("/").append(mMonth[0] + 1)
.append("/").append(mYear[0]).append(" "));
}
};
DatePickerDialog dialog = new DatePickerDialog(getActivity(), pDateSetListener, mYear[0], mMonth[0], mDay[0]);
dialog.getDatePicker().setMaxDate(new Date().getTime());
dialog.getDatePicker().setMinDate(new Date().getTime(),-year);
dialog.show();
break;
You can use Calendar class :
Calendar cal = Calendar.getInstance()
cal.add(Calendar.DATE, -7);
System.out.println("Date = "+ cal.getTime());
Joda-time is the best Java library for Date.
Get the date after subtracting 2 years :
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.YEAR, -2);
dialog.getDatePicker().setMinDate(calendar.getTime()); // set min date
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.
I have 3 strings containing day, month and year values. For example:
String mday = "02";
String mmonth="07";
String myear="2013";
I need to set the DatePicker in my activity to a month from the date above. I do not mean just add 1 to the mmonth value... in case of day 31 I would end up with an invalid date.
So I need some way to increment the date (the valid way) and set the DatePicker with it's value.
I am aware that setting the datePicker with Int values is done like this:
DatePicker datepicker = (DatePicker) findViewById(R.id.datePicker1);
datepicker.init(iYear, iMonth, iDay, null);
// where iYear,iMonth and iDay are integers
But how do I obtain the integer values of day,month and year of an incremented DATE by one month?
So between the first values (strings) and final values of incremented date(integers) what are the steps that I must make?
I assume I would have to use a Calendar.
So my code should look like this:
Integer iYear, iMonth, iDay = 0;
String mday = "02";
String mmonth="07";
String myear="2013";
Calendar cal = Calendar.getInstance();
cal.set(Integer.parseInt(myear), Integer.parseInt(mmonth), Integer.parseInt(mday));
cal.add(Calendar.MONTH, 1);
// here I should get the values from cal inside the iYear, iMonth, iDay, but I do not seem to succeed.
DatePicker datepicker = (DatePicker) findViewById(R.id.datePicker1);
datepicker.init(iYear, iMonth, iDay, null);
if I do:
datepicker.init(cal.YEAR, cal.MONTH, cal.DATE, null);
then application crashes.
What should I do?
How to set this incremented by a month date into my DatePicker?
UPDATE
I changed my test code to this:
Calendar cal = Calendar.getInstance();
cal.set(2013, 05, 23);
cal.add(Calendar.MONTH, 1);
int xxday = cal.get(Calendar.DATE);
int xxmonth = cal.get(Calendar.MONTH);
int xxyear = cal.get(Calendar.YEAR);
datepicker.init(xxyear, xxmonth, xxday, null);
but Now the datePicker is set to one month from NOW instead of one month from the wanted date So instead of (2013-06-23) I have (2013-09-23). I assume it's because of
int xxmonth = cal.get(Calendar.MONTH);
how can I get the real month from a Calendar cal; ?
DatePicker class has a method updateDate(year, month, dayOfMonth) which you can use to set a date in your DatePicker as shown below:
DatePicker datePicker = (DatePicker) findViewById(R.id.datePicker1);
datePicker.updateDate(2016, 5, 22);
Calendar month is 0 based. So month 07 is August.
Use the following code to initialize the calendar object if you have a date picker:
Calendar calendar = new GregorianCalendar(datePicker.getYear(),
datePicker.getMonth(),
datePicker.getDayOfMonth());
Else hard-code the date parts in the constructor
use this tuto to create your DatePickerDialog then use this code inside DatePickerDialog
https://developer.android.com/guide/topics/ui/dialogs.html
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
String mday = "02";
String mmonth="07";
String myear="2013";
//convert them to int
int mDay=Integer.valueOf(mday);
int mMonth=Integer.valueOf(mmonth);
int mYear=Integer.valueOf(myear);
return new DatePickerDialog(getActivity(), new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker datePicker, int i, int i1, int i2) {
String d=convertToCompletDate(i2,i1,i);
mListener.onDatePicked(d);
}
},mYear,mMonth,mDay);
}
In Kotlin
Assuming your date is a string. i.e:
var defaultDate = "20/4/2022"
you could use
val datePicker = findViewById<DatePicker>(R.id.date_Picker)
var defaultDate = eventDate.toString().split(Regex("/"))
var dd = defaultDate[0].toInt()
var mm = defaultDate[1].toInt()
var yy = defaultDate[2].toInt()
datePicker.updateDate(yy,mm,dd)
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;