Disables set of dates using materialdatetimepicker - android

I am using materialdatetimepicker to customise my calendar.
My requirement is I want to disable all dates from today and next 31 days.
What I have tried.
1 - Set the minimum date to Today - datePickerDialog.setMinDate(now);
2 - Maximum date to 31 days from today. - datePickerDialog.setMaxDate(cal);
3 - Disabled the dates in between. datePickerDialog.setDisabledDays(otherCalendars);
When I do step 1 2 and 3 together, the Calendar is not opened at all and app freezes.
When I do the steps (1,2) and 3 seperately I get the correct results. But I only want to display next 31days from now and disable them all.
Here is the code which I have tried.
Where am I getting this wrong? any help is much appreciated.
private DatePickerDialog datePickerDialog;
DateTime startDateTime = new DateTime();
DateTime endDateTime = new DateTime();
endDateTime = endDateTime.plusDays(31);
List<DateTime> otherDays = new ArrayList<>();
while (startDateTime.isBefore(endDateTime)) {
otherDays.add(startDateTime);
startDateTime = startDateTime.plusDays(1);
}
Calendar[] otherCalendars = new Calendar[otherDays.size()];
for (int count = 0; count < otherDays.size(); count++) {
otherCalendars[count] = otherDays.get(count).toGregorianCalendar();
}
datePickerDialog.setMinDate(now);
Calendar cal = Calendar.getInstance();
Date ddd = endDateTime.toDate();
cal.setTime(ddd);
datePickerDialog.setMaxDate(cal);
datePickerDialog.setDisabledDays(otherCalendars);
Thanks
R

I had the same issue and found solution for it here Disable whole week except weekend in calender
[disable-whole-week-except-weekends]
I used List with Calendar type List<Calendar> weekends = new ArrayList<>();
And fill it with days i want to disable.

Related

Difficulty getting data from Sqlite database between two days

I was doing an Android app that generates sales report for dates between the current date and seven days in the past. It worked fine, here's the code:
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.DAY_OF_YEAR,-7);
String currentDate = new SimpleDateFormat("dd-MM-yyyy").format(new Date());
SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");
String sevenDayAgo = sdf.format(calendar.getTime());
Cursor weeklyIncome = db.getResult("select sum(price) as total_income from sales where date between '"+sevenDayAgo+"' and '"+currentDate+"'");
Cursor weeklyCost = db.getResult("select sum(purchase_price * quantity) as total_cost from sales where date between '"+sevenDayAgo+"' and '"+currentDate+"'");
Say for example currentDate = 31-08-2018 and sevenDayAgo = 24-08-2018 this all worked fine but when I change my system date to the next day which is the next month and currentDate becomes 01-09-2018 the query doesn't return anything from the database, it should have returned records between 25-08-2018 and 01-09-2018 which has seven days in between. Somehow the query doesn't work when the 7 days are in two different months. I don't know what's going on and how to fix it.
p.s. The date column in sales table is of type TEXT.
The problem is the format you're using for dates (dd-mm-yyyy) isn't in lexicographic order. The string '25-08-2018' compares greater than '01-09-2018' . x BETWEEN y AND z is equivalent to x >= y AND x <= z. That condition won't be true for dates in that range using your format (Remember, they're just strings. sqlite does not have a date type.
You should be using ISO-8601 formats, like yyyy-mm-dd. These will sort properly ('2018-08-25' < '2018-09-01') and will allow you to use the sqlite3 date and time functions on them.
Suppose user has entered the birth date in 31/08/2018 this format :
Parse it like :
String[] parts = BirthField.getText().toString().trim().split("/");
int CAL_DAY, CAL_MONTH, CAL_YEAR;
if(parts.length == 3)
{
CAL_DAY = Integer.parseInt(parts[0]);
CAL_MONTH = Integer.parseInt(parts[1]);
CAL_YEAR = Integer.parseInt(parts[2]);
}
You can check if user has entered a good date or not with :
if( CAL_DAY > 0 && CAL_DAY < 32 && CAL_MONTH > 0 && CAL_MONTH < 13 && CAL_YEAR > 1900 )
While storing in database table take below care :
Calendar CalendarEvent = Calendar.getInstance(TimeZone.getDefault(), Locale.getDefault());
CalendarEvent.set(Calendar.DATE, CAL_DAY);
CalendarEvent.set(Calendar.MONTH, CAL_MONTH - 1);
CalendarEvent.set(Calendar.HOUR_OF_DAY, Integer.parseInt(ScheduleTime) );
CalendarEvent.set(Calendar.MINUTE, 00);
CalendarEvent.set(Calendar.SECOND, 00);
SimpleDateFormat format = new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss Z", Locale.getDefault());
String DayConsidered = format.format(CalendarEvent.getTime());
Please note CAL_MONTH - 1 as system starts months from 0 to 11
While storing store in database in SystemTime like :
SYSTIME = CalendarEvent.getTimeInMillis();
While using it again retrieve it from database and initialise calendar event with it like :
Calendar CalendarEvent = Calendar.getInstance();
CalendarEvent.setTimeInMillis( Long.parseLong(SYSTIME) );
int CAL_DAY = CalendarEvent.get(Calendar.DAY);
CalendarEvent.set(Calendar.DATE, CAL_DAY - 7);
And it will start working for even if days / months / even you change years from any date; it will always show the date which is less than 7 days
Hope it helps and let me know how it works as i am answering it quick...
Edit : 2
Better and most efficient way which i am using in my project and working perfectly is :
Log.d("ADDING A MONTH :", "ADDING 1 MONTH....\n");
CalendarEvent.add(Calendar.MONTH, 1);
Log.d("NEGATING 7 DAYS :", "NEGATING 7 DAYS....\n");
CalendarEvent.add(Calendar.DATE, -7);

Set minimum year (use to select DOB) for Datepicker dialog

I have create a function for my code which set a rule to restrict user to select the day earlier then systems date from date picker dialog
protected void setMinMax() {
Calendar minAllowedDate = CommUtils.getMinAllowedDate();
minAllowedDate.add(Calendar.MILLISECOND, -1000);
datePickerDialog.getDatePicker().setMinDate(minAllowedDate.getTimeInMillis());
now i want to create another date picker for user to select DOB, what i want to do is to set a rules that user DOB should be on age 4-150 which means the YEAR that user can select should be -4 & -150 from systems date. If using the the code above, what should i put in
minAllowedDate.add(Calendar.MILLISECOND, -1000);
i had tried with below code which give me the year 150 as min option
minAllowedDate.add(Calendar.YEAR, -150);
Use the below for minimum and maximum
Calendar calStart = new GregorianCalendar();
calStart.setTime(new Date());
calStart.add(Calendar.YEAR, -150);
Calendar calEnd = new GregorianCalendar();
calEnd.setTime(new Date());
calEnd.add(Calendar.YEAR, -4);
You can use android:startYear which will include the start year.
Look at the documentation here.
Found out that most of the solution using the method .add(Calendar.YEAR,-4), however this also create limit to the month & date to be select. For example, When the current date is 11/Jun/2018, running that line of code you can have 4 years before(2018-4=2014) but also limit in your month + day which you can only select date before 11/Jun/2018.
After several tried, i had came out the solution which manually set the day & month to 31/Dec so that i can have an option range from 31/12/2014 to 1/1/2014
Calendar calStart = new GregorianCalendar();
calStart.setTime(new Date());
calStart.set(Calendar.MONTH, 11);
calStart.set(Calendar.DAY_OF_MONTH, 31);
calStart.add(Calendar.YEAR, -150);
Calendar calEnd = new GregorianCalendar();
calEnd.setTime(new Date());
calEnd.set(Calendar.MONTH, 11);
calEnd.set(Calendar.DAY_OF_MONTH, 31);
calEnd.add(Calendar.YEAR,-4);
datePickerDialog.getDatePicker().setMinDate(calStart.getTimeInMillis());
datePickerDialog.getDatePicker().setMaxDate(calEnd.getTimeInMillis());

How show hh:mm in TextView?

I want show time in TextView using below code.
PersianCalendar persianCalendar = new PersianCalendar();
persianCalendar.setTime(mDate);
Calendar cal = Calendar.getInstance();
cal.setTime(mDate);
holder.tvTime.setText(cal.get(Calendar.HOUR_OF_DAY)+":"+cal.get(Calendar.MINUTE));
Problem occurs when time is for example 12:03 in TextView displayed as 12:3
How can I fix this?
You can format a Date to a String like this (using java.text.SimpleDateFormat)
holder.tvTime.setText(new SimpleDateFormat("H:mm").format(mDate));
The H format specifier means Hour in day (0-23), and the mm means Minute in hour with two digits.
See the documentation for other formatting options.
Use this code to format minute in 2 digits..
holder.tvTime.setText(String.format("%d:%02d",cal.get(Calendar.HOUR_OF_DAY), cal.get(Calendar.MINUTE));
Edit - As suggested by #henry.. you can directly go with this.. holder.tvTime.setText(String.format("%d:%02d",cal.get(Calendar.HOUR_OF_DAY), cal.get(Calendar.MINUTE));
I had same issue and solved by this.
Probably it is not the best solution, but it worked for me.
PersianCalendar persianCalendar = new PersianCalendar();
persianCalendar.setTime(mDate);
Calendar cal = Calendar.getInstance();
cal.setTime(mDate);
String minuteSelected = String.valueOf(cal.get(Calendar.MINUTE));
String minutWith0 = ((minuteSelected.length() == 1 ? "0" + minuteSelected : minuteSelected));// to get minut "01" insted of "1"
holder.tvTime.setText(cal.get(Calendar.HOUR_OF_DAY)+":"+ minutWith0);

Calendar allways returns the same date

I'm trying to get the current day of the week and week of the year like this:
Declaring my variable like this:
Calendar calWeek;
Calendar calDay;
Setting the values like this:
calWeek = Calendar.getInstance();
calWeek.setFirstDayOfWeek(Calendar.MONDAY);
calWeek.set(Calendar.WEEK_OF_YEAR, Calendar.MONDAY);
calDay = Calendar.getInstance();
calDay.setFirstDayOfWeek(Calendar.MONDAY);
calDay.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
int currentWeek = calWeek.get(Calendar.WEEK_OF_YEAR);
int dayInWeek = calDay.get(Calendar.DAY_OF_WEEK);
currentWeek returns 2 and dayInWeek returns 2. The current week is 1 and it's Wednesday. (3rd day of the week)
Even if i change the date on my device, the output is the same, currentWeek returns 2 and dayInWeek returns 2.
Why does it always return the same date?
Best regards,
Dridia
As mentioned in Mike M's comment: you set both values to Calendar.MONDAY which is equals to 2.
Calendar.getInstance() returns an instance with the current date but if you call calendarInstance.get(Calendar.WEEK_OF_YEAR) you still get 2 because according to the docs:
When setting or getting the WEEK_OF_MONTH or WEEK_OF_YEAR fields, Calendar must determine the first week of the month or year as a reference point. The first week of a month or year is defined as the earliest seven day period beginning on getFirstDayOfWeek() and containing at least getMinimalDaysInFirstWeek() days of that month or year....
I just tried it and getMinimalDaysInFirstWeek()returns 1 by default. So you should set this to 7 days. So the first Week will begin on Monday as you expect.
One instance of Calendar is sufficient and your code should look like this:
Calendar calendarInstance = Calendar.getInstance();
calendarInstance.setFirstDayOfWeek(Calendar.MONDAY);
calendarInstance.setMinimalDaysInFirstWeek(7);
int currentWeek = calendarInstance.get(Calendar.WEEK_OF_YEAR);
int dayInWeek = calendarInstance.get(Calendar.DAY_OF_WEEK);
System.out.println("week = " + currentWeek);
System.out.println("day of week = " + dayInWeek);
prints:
week = 1
day of week = 4
P.S. 4 means Wednesday

CalendarView can not setdate to current day?

Every time I try to set CalendarView to focus today (use setDate() to set), it always shows the last day which is available in the Calendar (31 November 2100).
But if i set date to another day it's work fine.
CalendarView cal = new CalendarView(this);
cal.setDate(new Date().getTime(),false,true);
CalendarView cal = new CalendarView(this);
cal.setDate(System.currentTimeMillis(),false,true);
or
cal.setDate(Calendar.getInstance().getTimeInMillis(),false,true);
This is waste of time + headache thing ,I really wonder why there are no one here answer this topic (3years ago!) /or why there is no any top search result in Google to answer this simple problem.
It's too sad that I can't never explain my rage with my bad English skill,
So I will just write it here for the other that will face this issue.
To convert DateTime of C# for Calendar View -> You must subtract tick count of this date 1/1/1970
public static long DatetimeToLong(DateTime dt) {
return (long)( dt - new DateTime(1970, 1, 1)).TotalMilliseconds ;
//(dt - (new DateTime(1970, 1, 1) ) );
}
Calendar_View.SetDate( util.DatetimeToLong(DateTime.Now.Date.AddDays(20) ) ,false ,true);
p.s. Conversion from milliseconds to DateTime format

Categories

Resources