Date dialog Gets forceclose when it comes to December month - java

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.

Related

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

Setting an alarm based on date in database

I found a tutorial that helped me get a working alarm setup but in the tutorial we used a date picker to set the time of the alarm. All was going well, so I attempted to replace the date picker with a method of my own and set the alarm that way. Problem is it doesn't seem to be working, no alarm pops up when I set that date to today but works fine when I use the date picker. Can anyone tell me what I'm doing wrong? I ran this through debug and my query is returning the proper date, I'm getting the right numbers and all but it doesn't seem to work.
I'm hoping someone can point out something I've missed?
EDIT
I call setNotif() through a button in the ui. I basically remodelled it to just have a button for testing. I get the toast but no alarm goes off no matter what I try.
Here's the original date picker code
public void onDateSelectedButtonClick(View v){
int day = picker.getDayOfMonth();
int month = picker.getMonth();
int year = picker.getYear();
Calendar c = Calendar.getInstance();
c.set(year, month, day);
c.set(Calendar.HOUR_OF_DAY, 0);
c.set(Calendar.MINUTE, 0);
c.set(Calendar.SECOND, 0);
scheduleClient.setAlarmForNotification(c);
Toast.makeText(this, "Notification set for: "+ day +"/"+ (month+1) +"/"+ year, Toast.LENGTH_SHORT).show();
}
Here's the method I tried to replace it with
It calls a query to get a specific date from my database and supposedly sets an alarm 3 days prior. I tested it by changing the date of my phone and by making it set the alarm to today as well but neither have worked.
public void setNotif() {
// Getting the next date of payments which the alarm will be based on
DatabaseHelper db = new DatabaseHelper(this);
String thisdate = getCurDate();
Cursor cur = db.nextdate(thisdate);
String date= "";
if (cur!= null) {
if (cur.moveToFirst()) {
date = cur.getString(0);
}
}
try {
DateFormat inputFormat = new SimpleDateFormat("yyyy-MM-dd");
Date input = inputFormat.parse(date);
String finaldate = inputFormat.format(input);
String d = finaldate.substring(8,10);
String m = finaldate.substring(5,7);
String y = finaldate.substring(0,4);
int da = Integer.parseInt(d);
int month = Integer.parseInt(m);
int year = Integer.parseInt(y);
int day = da - 3;
Calendar c = Calendar.getInstance();
c.set(year, month, day);
c.set(Calendar.HOUR_OF_DAY, 0);
c.set(Calendar.MINUTE, 0);
c.set(Calendar.SECOND, 0);
scheduleClient.setAlarmForNotification(c);
Toast.makeText(this, "Notification set for: "+ day +"/"+ month +"/"+ year, Toast.LENGTH_SHORT).show();
}catch (Exception ex) {
Alerts.CatchError(Kik.this, ex.toString());
}
}
This is an easy road block to run into, unfortunately and it doesn't really have anything to do with Android. It's a holdover from Java date/calendar.
When you pull the date out of the int month out of the date picker in the example code the value you get out is 0 based:
int month = picker.getMonth();
// January -> 0
// February -> 1
// ...
// December -> 11
The dates in your database are dates we're used to looking at: 2016-12-25 is December 25th, 2016.
When you set the values for Calendar it is expecting a 0-indexed month. You're giving it a 1-indexed month. So you'll need to subtract 1 from the month to get the right value. I'll make a table so it's clear what's going on:
Month String | Database Value | Calendar Value
January | 1 | 0
February | 2 | 1
March | 3 | 2
April | 4 | 3
May | 5 | 4
June | 6 | 5
Hopefully that makes it obvious.
So in your case if you change the line:
c.set(year, month, day);
To be...
c.set(year, month - 1, day);
You'll win.

How to check if the date belongs to current week or not? [duplicate]

This question already has answers here:
Get the week start and end date given a current date and week start
(4 answers)
Closed 8 years ago.
I have the date and time stored in preferences as Long:
// put
SharedPreferences settings =
PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
settings.edit().putLong("pref_datetime", System.currentTimeMillis()).commit();
// get
Date date2 = new Date(settings.getLong("pref_datetime", 0));
Once date is extracted, how could I check if it belongs to the current week (starting on Monday) or not?
You can use a Calendar instance to create this Monday and next Monday Date instances based on the current date then check that your date lies between them.
Calendar c = Calendar.getInstance();
c.setFirstDayOfWeek(Calendar.MONDAY);
c.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
c.set(Calendar.HOUR_OF_DAY, 0);
c.set(Calendar.MINUTE, 0);
c.set(Calendar.SECOND, 0);
c.set(Calendar.MILLISECOND, 0);
Date monday = c.getTime();
Date nextMonday= new Date(monday.getTime()+7*24*60*60*1000);
boolean isThisWeek = date2.after(monday) && date2.before(nextMonday);
You can construct a Calendar, and use getField(int) to get both the Calendar.YEAR and the Calendar.WEEK_OF_YEAR. When those are the same, the two Dates are from the same week.
When constructing the Calendar, also call setFirstDayOfWeek(Calendar.MONDAY) to make sure the weeks start on Monday (if you don't, it depends on the current locale).
After #SiKelly's objection that this won't work reliably in the end of December, beginning of January:
Compare WEEK_OF_YEAR.
If not equal, it is a different week.
If equal, it could be the wrong year, but that is hard to check. So just also check that the difference in getTime() is less than 8 * 24 * 60 * 60 * 1000 (eight days to be on the safe side).
(you could do step 3 first. then you avoid having to construct the calendar at all in many cases).
You can use Calendar to calculate week number for today and your date also,then simpy try to match it,
// put
SharedPreferences settings =
PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
settings.edit().putLong("pref_datetime", System.currentTimeMillis()).commit();
// get
Date date2 = new Date(settings.getLong("pref_datetime", 0));
Calendar calendar = Calendar.getInstance();
calendar.setFirstDayOfWeek(Calendar.MONDAY);
int current_year = calendar.get(Calendar.YEAR);
int current_week_number = calendar.get(Calendar.WEEK_OF_YEAR);
calendar.setTime(date2);
int year = calendar.get(Calendar.YEAR);
int week_number= calendar.get(Calendar.WEEK_OF_YEAR);
if(current_year==year && current_week_number==week_number)
{
//same
}
else
{
//different
}
try this
private boolean is_ThisWeek(Date date2){
Date now =new Date(System.currentTimeMillis());
int diffInDays = (int)( (now.getTime() - date2.getTime())
/ (1000 * 60 * 60 * 24) );
Calendar calendar = Calendar.getInstance();
calendar.setTime(now);
int reslut = calendar.get(Calendar.DAY_OF_WEEK);
int days_before = get_days_before(reslut);
if (diffInDays<days_before) {
Toast.makeText(this, "this week", Toast.LENGTH_SHORT).show();
return true;
}else {
Toast.makeText(this,"not this week", Toast.LENGTH_SHORT).show();
return false;
}
}
int get_days_before(int reslut){
int days_before = 0;
switch (reslut) {
case Calendar.MONDAY:
days_before=1;
break;
case Calendar.TUESDAY:
days_before=2;
break;
case Calendar.WEDNESDAY:
days_before=3;
break;
case Calendar.THURSDAY:
days_before=4;
break;
case Calendar.FRIDAY:
days_before=5;
break;
case Calendar.SATURDAY:
days_before=6;
break;
case Calendar.SUNDAY:
days_before=7;
break;
}
return days_before;
}

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

Calculate business days in java without saturdays, sunday and public holiday

i have a table in oracle where I saved the twelve public days in Mexico and I need to calculate a limit day since you registered
public Date calcularFechaLimite() {
try {
DiaFestivoDTO dia = new DiaFestivoDTO();
// Calendar fechaActual = Calendar.getInstance();
Calendar fechaL = Calendar.getInstance();
fechaL.add(Calendar.DATE, 3);
switch (fechaL.get(Calendar.DAY_OF_WEEK)) {
case Calendar.SATURDAY:
fechaL.add(Calendar.DATE, 2);
break;
case Calendar.SUNDAY:
fechaL.add(Calendar.DATE, 2);
break;
case Calendar.MONDAY:
fechaL.add(Calendar.DATE, 2);
break;
case Calendar.TUESDAY:
fechaL.add(Calendar.DATE, 1);
default:
break;
}
dia.setFechaLimite(fechaL.getTime());
Integer numeroDiasFest = seleccionPagoBO.obtenerDiasFestivos(dia);
if (numeroDiasFest != 0) {
fechaL.add(Calendar.DATE, numeroDiasFest);
dia.setFechaLimite(fechaL.getTime());
}
fechaLimite = fechaL.getTime();
} catch (Exception e) {
e.printStackTrace();
}
return fechaLimite;
}
This is what i have but March 28 and 29 are public days and it is not working, any idea??
Several issues:
You are not checking if the first 3 days you skip contain weekend days.
Also you are skipping strange amounts of days and skipping for weekdays as well (which are business days and therefore should not be skipped).
I assume the method DiaFestivoDTO.obtenerDiasFestivos() calculates the number of national holidays in a certain date range but what is the start date? Is it initialized to the current date when DiaFestivoDTO is created?
When there is a national holiday in your date range you increase the date range but never check if this new daterange includes new national holidays or weekend days.
If what you are trying to do is calculate a date '3 business days from now' here's roughly what I would do:
// get all the holidays as java.util.Date
DiaFestivoDTO dia = new DiaFestivoDTO();
List<Date> holidays = dia.getAllNationalHolidays();
// get the current date without the hours, minutes, seconds and millis
Calendar cal = Calendar.getInstance();
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
// iterate over the dates from now and check if each day is a business day
int businessDayCounter = 0
while (businessDayCounter < 3) {
int dayOfWeek = cal.get(Calendar.DAY_OF_WEEK);
if (dayOfWeek != Calendar.SATURDAY && dayOfWeek != Calendar.SUNDAY && !holidays.contains(cal.getTime())) {
businessDayCounter++;
}
cal.add(Calendar.DAY_OF_YEAR, 1);
}
Date threeBusinessDaysFromNow = cal.getTime();
For this to work I would advise you to add a new method 'getAllNationalHolidays' to list al the holidays because it is more efficient to store twelve dates in memory than to access the database multiple times to check for them.
If you cannot change/add database methods then you could do this
while (businessDayCounter < 3) {
// determine if this day is a holiday
DiaFestivoDTO dia = new DiaFestivoDTO();
dia.setFechaInitial(cal.getTime());
dia.setFechaLimite(cal.getTime());
boolean isHoliday = seleccionPagoBO.obtenerDiasFestivos(dia) > 0;
int dayOfWeek = cal.get(Calendar.DAY_OF_WEEK);
if (dayOfWeek != Calendar.SATURDAY && dayOfWeek != Calendar.SUNDAY && !isHoliday) {
businessDayCounter++;
}
cal.add(Calendar.DAY_OF_YEAR, 1);
}
Here I assumed you can set the 'from' date in your DiaFestivoDTO using 'setFechaInitial' or something like that. But in this way you would be calling the database at least three times which is inefficient.

Categories