getdate from datepicker android - java

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}"

Related

How to get int to a SimpleDateFormat

I have a method that collect the year, month and day from a DatePicker and stores them in separate integers.
public void onDateChanged(DatePicker datePicker, int year, int month, int dayOfMonth) {
yearD = year;
monthD = (month + 1);
dayD = dayOfMonth;
}
How can I transform these integers to a SimpleDateFormat with the pattern "yyyy-MM-dd"?
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
First you create a calendar object such as
Calendar c = Calendar.getInstance();
c.set(year, month - 1, day, 0, 0);
Now format as per your requirement as below
Date date = c.getTime();
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
String strDate = dateFormat.format(date);
Though I have not tested the code on IDE but I hope it will give you the solution.
I guess that should do the trick:
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
Calendar cal = new Calendar().set(year, month, day);
formatter.format(cal);
Even though this is not strictly an answer, I would recommend you to jump from the old and error prune Calendar / DatePicker classes, to the intuitive new LocalDate class. If you are interested, let me know and I'll tell you how :)

How to make DatePickerDialog's setMinDate different from "setCurrentDate"?

I'm using a DatePickerDialog to select a begin / end Date to search in an article list.
Thing is DatePickerDialog's setMinDate actually set also default position of dialog box when opened and block user from selecting an anterior date:
Here's my date gestion method:
private void createDisplay(DatePickerDialog.OnDateSetListener dateSetListener) {
Calendar cal = Calendar.getInstance();
int day = cal.get(Calendar.DAY_OF_MONTH);
int month = cal.get(Calendar.MONTH);
int year = cal.get(Calendar.YEAR);
DatePickerDialog dialog = new DatePickerDialog(
Objects.requireNonNull(getActivity()),
R.style.DatePickerDialogTheme,
dateSetListener,
day, month, year);
dialog.getDatePicker().setMaxDate(cal.getTimeInMillis());
cal.add(Calendar.YEAR, -5);
dialog.getDatePicker().setMinDate(cal.getTimeInMillis());
dialog.show();
}
I mean, it should be today as default position but if I use setMinDate I can't select an anterior position of today's date...
Use it like this -
Example:
// Adding 3 days
calendar.add(Calendar.DATE, 3);
// Set the Calendar new date as maximum date of date picker
dpd.getDatePicker().setMaxDate(calendar.getTimeInMillis());
// Subtract 6 days from Calendar updated date
calendar.add(Calendar.DATE, -6);
// Subtract 6 months from Calendar updated date
calendar.add(Calendar.MONTH, -6);
Or you can use
dpd.getDatePicker().setMinDate(new Date().getTime());
Note - put any date as you wish and modify it like this:
SimpleDateFormat formatter = new SimpleDateFormat("dd.MM.yyyy, HH:mm");
formatter.setLenient(false);
Date curDate = new Date();
long curMillis = curDate.getTime();
String curTime = formatter.format(curDate);
String oldTime = "05.01.2011, 12:45";
Date oldDate = formatter.parse(oldTime);
long oldMillis = oldDate.getTime();
And then
dpd.getDatePicker().setMinDate(oldMillis);

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);
}
}
});`

Android store valid dates (not dates in past)

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

Categories