I have a textview and when I click on it, datepicker dialog opens up. I am trying to display today's date on the datepicker dialog. If today is October 11, 2021, the datepicker dialog shows Novermber 11, 2021. But when I select the dates, the textview shows the correct date which is October 11, 2021. The problem is the month which is for some reason up by one.
public View.OnClickListener openDatePicker = new View.OnClickListener() {
#Override
public void onClick(View view) {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd", Locale.ENGLISH);
String todaysDate = LocalDate.now().toString();
Log.i("todays date", todaysDate);
LocalDate localDate = LocalDate.parse(todaysDate, formatter);
openDatePickerForParty(localDate);
}
};
public void openDatePickerForParty(LocalDate givenLocalDT){
DatePickerDialog startDateDialog = new DatePickerDialog(this, new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker datePicker, int year, int month, int day) {
AddNewEventScreen.this.textViewEventDate.setText(year + "-"+ (month) + "-" + day);
}
}, givenLocalDT.getYear(), givenLocalDT.getMonthValue(), givenLocalDT.getDayOfMonth());
Log.i("thismonth", String.valueOf(givenLocalDT.getMonthValue()));
startDateDialog.show();
}
The Log "thismonth" also displays the correct month of 10.
The reason for confusion here is the fact that DatePickerDialog widget accepts month value from 0 to 11.
monthOfYear -----> int: the initially selected month of the year (0-11 for compatibility with Calendar#MONTH)
So when you pass 10 for October for it its November. Just subtract the month value by 1 before initializing the DatePickerDailog and then its all fine. More info here
Related
I have one activity that i use to create customer, in this activity i have one edit text that can show the current date when user open screen. its can be change to future date but not past date so i have used
d2.getDatePicker().setMinDate(System.currentTimeMillis() - 1000);
to set current date as a minimum date and onClick i have opening DatePickerDialog. But, when click on that edit text app is crashed and this error show in Logcat.
java.lang.IllegalArgumentException: fromDate: Wed Aug 22 16:31:24
GMT+05:30 2018 does not precede toDate: Wed Aug 22 00:00:00 GMT+05:30
2018
here is my edittext onClickListner code.
Calendar cal = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat(DateUtil.dateFormatForDOB);
try {
cal.setTime(sdf.parse(edt.getText().toString()));
} catch (ParseException e) {
e.printStackTrace();
}
DatePickerDialog d2 = new DatePickerDialog(CreateUpdateOpportunityActivity.this, android.R.style.Theme_Holo_Light_Dialog_NoActionBar_MinWidth,
new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker view, int years,
int monthOfYear, int dayOfMonth) {
year = years;
month = monthOfYear;
day = dayOfMonth;
tv.setText(DateUtil.getDateOfBirth(year + "-" + (month + 1) + "-" + day));
}
}, year, month, day);
d2.getDatePicker().setSpinnersShown(true);
d2.getDatePicker().setCalendarViewShown(false);
d2.updateDate(cal.get(Calendar.YEAR), cal.get(Calendar.MONTH), cal.get(Calendar.DAY_OF_MONTH));
d2.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
d2.getDatePicker().setMinDate(System.currentTimeMillis() - 1000);
d2.show();
d2.setCanceledOnTouchOutside(false);
i used other solution like
d2.getDatePicker().setMinDate(System.currentTimeMillis());
or
d2.getDatePicker().setMinDate(new Date().getTime() - 10000);
but still app crash and same error comes
if i comment above line of code, my app run without crash.
you need to check if calendar date(cal.getTimeInMillis()) is greeter then your current date(System.currentTimeMillis())
like this
if (cal.getTimeInMillis() < System.currentTimeMillis()) {
// Toast.makeText(getApplicationContext(),"Current time is big",Toast.LENGTH_SHORT).show();
d2.getDatePicker().setMinDate(cal.getTimeInMillis());
} else {
// Toast.makeText(getApplicationContext(),"Current time is small",Toast.LENGTH_SHORT).show();
d2.getDatePicker().setMinDate(System.currentTimeMillis());
}
may be this help
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
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));
}
};
I have a serious problem here, I am building an app that will work on Arabic devices, and I need to send dates to the server, I am using Android DatePickerDialog to get the date, but the date always sent with Arabic characters, and when i try to display it again it gives me Unparsable date exception
I have tried the following solutions but no results
mDateTime = Calendar.getInstance(Locale.US).getTime();
mDateFormater.setTimeZone(TimeZone.getTimeZone("GMT"));
but non of them worked for me
any help please.
My date picker dialog code is like following
public static class DatePickerFragment extends DialogFragment implements
DatePickerDialog.OnDateSetListener {
private TextView mUserView;
private Date mAffectedDate;
private SimpleDateFormat mDateFormater;
private Date mInitialDate;
public TextView getUserView() {
return mUserView;
}
public void setUserView(TextView userView) {
this.mUserView = userView;
}
public Date getAffectedDate() {
return mAffectedDate;
}
public void setAffectedDate(Date mAffectedDate) {
this.mAffectedDate = mAffectedDate;
}
public SimpleDateFormat getDateFormater() {
return mDateFormater;
}
public void setDateFormater(SimpleDateFormat mDateFormater) {
this.mDateFormater = mDateFormater;
}
public Date getInitialDate() {
return mInitialDate;
}
public void setInitialDate(Date mInitialDate) {
this.mInitialDate = mInitialDate;
}
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Use the current date as the default date in the picker
final Calendar c = Calendar.getInstance(Locale.US);
c.setTime(mInitialDate);
int year = c.get(Calendar.YEAR);
int month = c.get(Calendar.MONTH);
int day = c.get(Calendar.DAY_OF_MONTH);
// Create a new instance of DatePickerDialog and return it
return new DatePickerDialog(getActivity(), this, year, month, day);
}
public void onDateSet(DatePicker view, int year, int month, int day) {
Date date = new Date();
date.setYear(year - 1900);
date.setMonth(month);
date.setDate(day);
mAffectedDate.setYear(year - 1900);
mAffectedDate.setMonth(month);
mAffectedDate.setDate(day);
mUserView.setText(mDateFormater.format(date));
}
}
You can use:
Calendar.set(int year, int month, int day, int hourOfDay, int minute, int second)
Sets the year, month, day of the month, hour of day, minute, and second fields. Other fields are not
changed; call clear first if this is not desired. The month value is 0-based, so it may be clearer to use a constant like JANUARY.
Like this:
Calendar cal = Calendar.getInstance(Locale.US);
public void onDateSet(DatePicker view, int year, int month, int day) {
cal.set(year, month, day, 0, 0, 0);
// get time in milliseconds
Long timeInmilliseconds = cal.getTimeInMillis();
// print time
Log.v("log", "Date "+ new Date(cal.getTimeInMillis()));
}
Also see this:
A common mistake is to implicitly use the default locale when producing output meant to be machine-readable. This tends to work on the developers test devices (especially because so many developers use en_US), but fails when run on a device whose user is in a more complex locale.
For example, if you are formatting integers some locales will use non-ASCII decimal digits. As another example, if you are formatting floating-point numbers some locales will use ',' as the decimal point and '.' for digit grouping. That is correct for human-readable output, but likely to cause problems if presented to another computer (parseDouble(String) cannnot parse such a number, for example).
When i press the button to display the DatePickerDialog, the dialog displays one month greater. For instance, if i initiate with the current date like this(with the DateTime of joda library):
DateTimeZone zone = DateTimeZone.forID("Europe/Athens");
DateTime dt = new DateTime(zone);
int year = dt.getYear();
int month = dt.getMonthOfYear();
int day = dt.getDayOfMonth();
which is 07/08/2014, the date dialog displays one month greater 07/09/2014.
I do not understand why this happens.
The fragment which represents the datePickerFragment is:
#SuppressLint("ValidFragment")
public class DatePickerFragment extends DialogFragment implements DatePickerDialog.OnDateSetListener{
#SuppressLint("ValidFragment")
TextView txtDate;
GlobalData appState;
public DatePickerFragment(TextView txtDate) {
super();
this.txtDate = txtDate;
}
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Use the current date as the default date in the picker
DateTimeZone zone = DateTimeZone.forID("Europe/Athens");
DateTime dt = new DateTime(zone);
int year = dt.getYear();
int month = dt.getMonthOfYear();
int day = dt.getDayOfMonth();
Log.i("DatePickerFragment day month year", day +" "+ month + " "+ year + "");
// Create a new instance of DatePickerDialog and return it
return new DatePickerDialog(getActivity(), this, year, month, day);
}
public void onDateSet(DatePicker view, int year, int month, int day) {
appState.setDateUserFrom(year, month, day);
Log.i("Date day month yerar", "Date changed." + day+" " + month + " " +year);
txtDate.setText(new StringBuilder().append(day)
.append("-").append(month).append("-").append(year)
.append(" "));
}
}
DatePickerDialog takes monthOfYear that is 0 to 11 [0 for Jan... 11 for Dec], and your DateTime returns 1 to 12. So you need to do -1 with month value.
Use this:
return new DatePickerDialog(getActivity(), this, year, month - 1, day);
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Use the current date as the default date in the picker
DateTimeZone zone = DateTimeZone.forID("Europe/Athens");
DateTime dt = new DateTime(zone);
int year = dt.getYear();
int month = dt.getMonthOfYear()-1;
int day = dt.getDayOfMonth();
Log.i("DatePickerFragment day month year", day +" "+ month + " "+ year + "");
// Create a new instance of DatePickerDialog and return it
return new DatePickerDialog(getActivity(), this, year, month, day);
}
Month in date picker starts with zero. So you should subtract one from the getMonthOfYear() to set it on datepicker.
I am pretty sure the reason behind this is because the Android DatePickerDialog expects 0 based month values. Jodatime return them as you would expect it (more human friendly). So just subtract 1 from the month.
Just to clarify, most date functions/libraries are designed with 0 based month values by default. The exception is where explicitly noted, or third party libraries like Jodatime, which make working with date stuff a joy.
Just a guess. Joda month starts at 1 for january but java date at 0? So if you use the current date init with joda the date picker will show the wrong month. Easy solution:
month = dt.getMonthOfYear() - 1;
Try this hope it's worked:
DateTimeZone zone = DateTimeZone.forID("Europe/Athens");
DateTime dt = new DateTime(zone);
int year = dt.getYear();
int month = dt.getMonth();
int day = dt.getDayOfMonth();
OR
DateTimeZone zone = DateTimeZone.forID("Europe/Athens");
DateTime dt = new DateTime(zone);
int year = dt.getYear();
int month = dt.getMonthOfYear() - 1;
int day = dt.getDayOfMonth();