Android store valid dates (not dates in past) - java

Not sure why, but Im trying to set a valid (one that isn't in the past). This works in some cases, e.g. set to April 4th 2014, however if I am setting it from Feb 28th 2014 to March 2nd 2014, It is saying the date is a date in the past. Can someone see why this is the case?
public class StartDatePicker extends DialogFragment implements
DatePickerDialog.OnDateSetListener {
Calendar c = Calendar.getInstance();
int startYear = c.get(Calendar.YEAR);
int startMonth = c.get(Calendar.MONTH);
int startDay = c.get(Calendar.DAY_OF_MONTH);
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Use the current date as the default date in the date picker
DatePickerDialog dialog = new DatePickerDialog(getActivity(), this,
startYear, startMonth, startDay);
return dialog;
}
#Override
public void onDateSet(DatePicker view, int year, int monthOfYear,
int dayOfMonth) {
// disable past dates
if (year < startYear || monthOfYear < startMonth
|| dayOfMonth < startDay) {
DialogFragment dialogFragment = new StartDatePicker();
dialogFragment.show(getSupportFragmentManager(),
"start_date_picker");
Toast.makeText(getApplicationContext(), "Select Valid Date",
Toast.LENGTH_LONG).show();
} else {
//store date
}}

If you want to check if selected date is in past use the following:
on your onDateSet function - create a calendar instance and :
calendar.set(Calendar.YEAR,year);
calendar.set(Calendar.MONTH,monthOfYear);
calendar.set(Calendar.DAY_OF_MONTH,dayOfMonth);
After setting a calendar with the date picked, check if it's past/after your current time using System.timeInMilliseconds()
if (calendar.getTimeInMilliseconds() < System.timeInMilliseconds()) {
// Your implementation ...
}
Hope it helpes...good luck

Related

Calendar Object seams not to be handed to the method using Android and datepicker [duplicate]

This question already has answers here:
Java Calendar always shows the same time
(5 answers)
Can't add days to Calendar
(1 answer)
Closed 4 years ago.
I have a silly beginner question.
I am using the Andriod datepicker to do some data entry. Overall I want to store and retrieve data from a firestore db.
But currently I am struggling with with Calendar and datepicker. The last method (updateDatepickerFromCalendar) is used to update the datapicker with the new data once retrieved. You will not find that one ... but I added a tempory Calendar object which also fails.
The other way around to update the Calendar object from the date picker works perfekt. But if I want to update the date picker from the Calendar object it seams that the calendar object is not handed to the method updateDatepickerFromCalendar while the datepicker object is.
Any Idea what I am doing wrong?
// retrieve data
ladeknopf.setOnClickListener( (View v) -> {
eingabename.setText(datensatz.getNameDerPerson());
Calendar testDatum; // just for testing
testDatum = Calendar.getInstance();
testDatum.set(1999,11,2);
updateDatepickerFromCalendar(testDatum, eingabedatum);
eingabeueberbblick.setText(datensatz.valuesToString());
});
}
// Datepicker Hilfsmethoden
// calendar object mit Daten aus Datepicker
private void updateCalendarFromDatepicker(Calendar cal3, DatePicker dp){
cal3.set(Calendar.YEAR, dp.getYear());
cal3.set(Calendar.MONTH, dp.getMonth());
cal3.set(Calendar.DAY_OF_MONTH, dp.getDayOfMonth());
}
// here is the issue: pb is handed over but the Calendar Object not
private void updateDatepickerFromCalendar(Calendar cal2, DatePicker dp) {
dp.updateDate(cal2.YEAR, cal2.MONTH, cal2.DAY_OF_MONTH);
}
Thank you in advance.
This example can help you.
DatePickerDialog[] datePickerDialog = new DatePickerDialog[1];
Calendar c = Calendar.getInstance();
int mYear = c.get(Calendar.YEAR); // current year
int mMonth = c.get(Calendar.MONTH); // current month
int mDay = c.get(Calendar.DAY_OF_MONTH); // current day
// date picker dialog
datePickerDialog[0] = new DatePickerDialog(RegistrationActivity.this,
new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker view, int year,
int monthOfYear, int dayOfMonth) {
// set day of month , month and year value in the edit text
dateOfBirth.setText(year + "-"+(monthOfYear + 1)
+ "-" + dayOfMonth);
}
}, mYear, mMonth, mDay);
datePickerDialog[0].show();

How to disable the previous dates in date picker dialogue box [duplicate]

This question already has answers here:
How to disable past dates in Android date picker?
(14 answers)
Closed 6 years ago.
I'm a student and I'm working on an android reservation app.In these app I have a button that choose date, when I click on the button a dialogue box appear for choosing the date, but I want to disable all the previous dates and just want to show current date and further 3 dates of a month.kindly help me how can I do this Thanks
pPickDate.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
showDialog(DATE_DIALOG_ID);
}
});
final Calendar cal = Calendar.getInstance();
pYear = cal.get(Calendar.YEAR);
pMonth = cal.get(Calendar.MONTH);
pDay = cal.get(Calendar.DAY_OF_MONTH);
/** Display the current date in the TextView */
updateDisplay();
}
protected Dialog onCreateDialog(int id) {
switch (id) {
case DATE_DIALOG_ID:
return new DatePickerDialog(this,
pDateSetListener,
pYear, pMonth, pDay);
}
return null;
}
private void updateDisplay() {
pDisplayDate.setText(
new StringBuilder()
// Month is 0 based so add 1
.append(pMonth + 1).append("/")
.append(pDay).append("/")
.append(pYear).append(" "));
}
You can set a min and max date for DatePicker, do something like this:
yourDatePickerDialog.getDatePicker().setMinDate(youMinDate);
https://developer.android.com/reference/android/widget/DatePicker.html#setMinDate(long)
try this one
DatePickerDialog datePicker;
private Calendar calendar;
private int year, month, day;
// FETCH YEAR,MONTH,DAY FROM CALENDAR
calendar = Calendar.getInstance();
year = calendar.get(Calendar.YEAR);
month = calendar.get(Calendar.MONTH);
day = calendar.get(Calendar.DAY_OF_MONTH);
datePicker = new DatePickerDialog(this, YOUR_LISTENER, year, month, day);
// this line is used for disable previous date but u can select the date
datePicker.getDatePicker().setMinDate(System.currentTimeMillis());
// this line is used to prevent date selection
datePicker.getDatePicker().setCalendarViewShown(false);

How can I setMaxDate() for DatePicker to one month after the current date?

Here's my onCreateDialog:
DatePickerDialog dialog = new DatePickerDialog(this, dpickerListener, year_x, month_x, day_x);
dialog.getDatePicker().setMinDate(System.currentTimeMillis() - 1000);
dialog.getDatePicker().setMaxDate();
As you can see, setMaxDate() is empty. I want to set the max date of the datePickerDialog to one month after the current date.
Here's how I get the current date:
cal2 = Calendar.getInstance();
currentDay = cal2.get(Calendar.DAY_OF_MONTH);
currentMonth = cal2.get(Calendar.MONTH);
currentYear = cal2.get(Calendar.YEAR);
currentDate = new Date();
currentDate.setDate(currentDay);
currentDate.setMonth(currentMonth);
currentDate.setYear(currentYear);
Use this snippet
Calendar cal=Calendar.getInstance()
cal.add(Calendar.MONTH,1)
long afterTwoMonthsinMilli=cal.getTimeInMillis()
DatePickerDialog.getDatePicker().setMaxDate(afterTwoMonthsinMilli);
It reads the current system date into a calendar object and adds 1 to the specified field,In this case MONTH and returns a calendar object
Similarly if you want to add values to other fields,Specify the field in the field type as:
Calendar.DAY_OF_MONTH
Calendar.YEAR
Calendar.HOUR
etc.
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.MONTH, 1);
dialog.getDatePicker().setMaxDate(calendar.getTimeInMillis);
You can use "add" to add to the Calendar.MONTH
you have to override OnDateChangedListener
`new OnDateChangedListener() {
public void onDateChanged(DatePicker view, int year,
int month, int day) {
Calendar newDate = Calendar.getInstance();
newDate.add(Calendar.MONTH, 1);
if (calendar.before(newDate)) {
view.init(minYear, minMonth, minDay, this);
}
}
});`

Date dialog Gets forceclose when it comes to December month

When i click on Dialog it gets Forceclose. works fine till November. but when i select December it gets forceclose. please see the code.
// ---------------- For DatePicker ----------------
#Override
protected Dialog onCreateDialog(int id) {
if(date.toString().length() > 0)
{
//12/31/1986
cmonth =(Integer.parseInt(date.substring(0,2)));
cday =(Integer.parseInt(date.substring(3,5)));
cyear =(Integer.parseInt(date.substring(6,10)));
}
else
{
Calendar c = Calendar.getInstance();
cyear = c.get(Calendar.YEAR);
cmonth = c.get(Calendar.MONTH);
cday = c.get(Calendar.DAY_OF_MONTH);
}
switch (id) {
case DATE_DIALOG_ID:
//return new DatePickerDialog(ProfileSetting.this, mDateSetListener, cyear, cmonth-1, cday); //Gets forceclose when it comes to December month
return new DatePickerDialog(ProfileSetting.this, mDateSetListener, cyear, cmonth, cday); // works till November
}
return null;
}
After thorough observation of your code pasted in Question, it was a mistake done by you.
in the first if loop of the onCreateDialog() you are getting the date in this format 12/31/1986. in which you are taking month as 12.
and in the else loop you take month directly from Calendar instance which will give you only upto 11.
So to work in both conditions you need to do decrement of month in first if loop.
Change your if loop as below
if(date.toString().length() > 0)
{
//12/31/1986
cmonth =(Integer.parseInt(date.substring(0,2)));
cmonth--;
cday =(Integer.parseInt(date.substring(3,5)));
cyear =(Integer.parseInt(date.substring(6,10)));
}
Hope it will works for you.

getdate from datepicker android

I want to get date from datepicker widget in android I have tried with this
Date date1= (Date) new Date
(dpBirthDate.getYear(), dpBirthDate.getMonth(), dpBirthDate.getDayOfMonth());
date1 = (Date) new SimpleDateFormat("yyyy-MM-dd").parse(date1.toString());
But I get a date like this mon 7 dec 2011 time ... and all I want to get is the yyyy-MM-dd format to store it in the database.
I tried also to concat the year-month-day like this but the problem is for example today
2011-12-7 the day should be 07 to be valid
Could you help me please.
I use this:
/**
*
* #param datePicker
* #return a java.util.Date
*/
public static java.util.Date getDateFromDatePicker(DatePicker datePicker){
int day = datePicker.getDayOfMonth();
int month = datePicker.getMonth();
int year = datePicker.getYear();
Calendar calendar = Calendar.getInstance();
calendar.set(year, month, day);
return calendar.getTime();
}
You should use SimpleDateFormat.format to convert that Date object to a String, like this
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String dateString = sdf.format(date1);
I think you just had it backwards. You need to use format to go from Date to String, and parse to go from a String to a Date.
I know this is old but i struggled to find it. So for posterity
Scenario: A View needs the date in yyyy-mm-dd
date_field = (EditText)findViewById(R.id.input_date);
date_field.setFocusable(false); // disable editing of this field
date_field.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(final View v) {
chooseDate();
}
});
private void chooseDate() {
final Calendar calendar = Calendar.getInstance();
final int year = calendar.get(Calendar.YEAR);
final int month = calendar.get(Calendar.MONTH);
final int day = calendar.get(Calendar.DAY_OF_MONTH);
DatePickerDialog datePicker =
new DatePickerDialog(this, new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(final DatePicker view, final int year, final int month,
final int dayOfMonth) {
#SuppressLint("SimpleDateFormat")
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
calendar.set(year, month, dayOfMonth);
String dateString = sdf.format(calendar.getTime());
date_field.setText(dateString); // set the date
}
}, year, month, day); // set date picker to current date
datePicker.show();
datePicker.setOnCancelListener(new DialogInterface.OnCancelListener() {
#Override
public void onCancel(final DialogInterface dialog) {
dialog.dismiss();
}
});
}
Hope this helps someone
If your formatting was simple as numbers,
eg: dd/MM/yyyy
You can use the Kotlin way:
val dp = binding.datePicker
val date = "${dp.dayOfMonth.let { if(it < 10) "0$it" else it }}/${dp.month.plus(1).let { if(it < 10) "0$it" else it }}/${dp.year}"

Categories