java


Convert int to Calendar Object


I am working in a Calendar Project and using this Github project:
https://github.com/wdullaer/MaterialDateTimePicker
I got the calendar working but my requirement is to disable all the weekdays and enable only Saturday and Sunday.
The library has a functionality as datepickerdialog.setDisabledDays() in which we have to pass the Calendar[].
If I add Calendar.Monday to the array (which returns int value), it throws an error like
setDisabledDays (java.util.Calendar[]) in DatePickerDialog cannot be applied to (int)
What I basically try to do is, to add all the weekdays in a Calendar array to disable them. So, how to convert int value to Calendar in Java?
Yes #OleV.V. Any idea on how to do it?
Yes and no. I would use ZonedDateTime for the calculations, and this is not readily available in your Android Java 7. If you are going to do more work with dates and/or times in your app and/or you foresee maintaining it for the years to come, you should consider using the ThreeTen ABP library. This gives you the date and time classes described in JSR-310. These are the ones to use for dates and times in 2017. Also because Stack Overflow is supposed to be a knowledge base, I will present this option first and the one without JSR-310 afterwards.
You asked about what to pass to setDisabledDays(). As I read your link, you would need to pass an array containing all the days that the user is not allowed to pick. In principle that’s infinitely many days. So you first need to decide how far into the past and/or the future the user really needs to select a day. Then force the user within your limit so you can control the pick. Next I think that it’s much easier to control it through setSelectableDays. This will control both the bounds and the days of week, and there are fewer Saturdays and Sundays than weekdays, so you will need a shorter array.
Edit: In my code below I have assumed that the user must pick a Saturday or Sunday within a time range from 1 year 6 months ago till 1 month into the future. I trust you to set the right bounds for you.
Modern solution
// start 1 year 6 months before today
// please change to the number of years, months, weeks and/or days you require
ZonedDateTime start = ZonedDateTime.now(ZoneId.systemDefault()).minusYears(1).minusMonths(6);
// end 1 month after today - also change to your own requirements
ZonedDateTime end = ZonedDateTime.now(ZoneId.systemDefault()).plusMonths(1);
List<Calendar> satsAndSuns = new ArrayList<>(200);
ZonedDateTime current = start;
if (current.getDayOfWeek().equals(DayOfWeek.SUNDAY)) {
satsAndSuns.add(GregorianCalendar.from(current));
}
current = current.with(TemporalAdjusters.nextOrSame(DayOfWeek.SATURDAY));
while (! current.isAfter(end)) {
satsAndSuns.add(GregorianCalendar.from(current));
// add 1 day to get Sunday
current = current.plusDays(1);
assert current.getDayOfWeek().equals(DayOfWeek.SUNDAY);
if (current.isAfter(end)) {
break;
}
satsAndSuns.add(GregorianCalendar.from(current));
// add 6 days to get Saturday
current = current.plusDays(6);
assert current.getDayOfWeek().equals(DayOfWeek.SATURDAY);
}
Calendar[] selecatbleDays = satsAndSuns.toArray(new Calendar[satsAndSuns.size()]);
Edit: I have used GregorianCalendar.from(current) for converting from ZonedDateTime to the Calendar object that MaterialDateTimePicker needs. This method does not exist on Android. According to the docs and with thanks to Basil Bourque you should instead use DateTimeUtils.toGregorianCalendar(current).
Running the above snippet on my computer today produced an array of 165 Calendar objects, all Saturdays and Sundays.
Oldfashioned solution
Use this solution if you do not want to depend on ThreeTen ABP. The algorithm to use is the same as above, only the details are different:
Calendar end = new GregorianCalendar(TimeZone.getDefault());
end.add(Calendar.MONTH, 1);
List<Calendar> satsAndSuns = new ArrayList<>(200);
// start 1 year 6 months before today
Calendar current = new GregorianCalendar(TimeZone.getDefault());
current.add(Calendar.YEAR, -1);
current.add(Calendar.MONTH, -6);
if (current.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY) {
// we need to add a copy because we will continue to modify current
// I really don’t like using clone(), but it’s the simplest way
satsAndSuns.add((Calendar) current.clone());
}
// Set current to next saturday
// This is where Calendar is not so straightforward as ZonedDateTime
// Subtraction of day of week works because in Calendar, Saturday is the last day of the week
current.add(Calendar.DATE, Calendar.SATURDAY - current.get(Calendar.DAY_OF_WEEK));
assert current.get(Calendar.DAY_OF_WEEK) == Calendar.SATURDAY;
while (! current.after(end)) {
satsAndSuns.add((Calendar) current.clone());
current.add(Calendar.DATE, 1);
assert current.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY;
if (current.after(end)) {
break;
}
satsAndSuns.add((Calendar) current.clone());
current.add(Calendar.DATE, 6);
assert current.get(Calendar.DAY_OF_WEEK) == Calendar.SATURDAY;
}
Calendar[] selecatbleDays = satsAndSuns.toArray(new Calendar[satsAndSuns.size()]);
.equals() or == with enums?
Edit: It’s not really part of the question, but now we came to debate it: I had first used current.getDayOfWeek() == DayOfWeek.SUNDAY because I find it a bit simpler to read than .equals(). It works because DayOfWeek is an enum and the JVM guarantees there is only one instance of each enum constant. Please find the objections in the comments. Basil Bourque has a point in teaching young programmers first and foremost to use .equals() for comparing objects for identity. Many have used long hours searching for a bug caused by using == between strings or other objects.
Calendar.Monday is just a constant for an int not a Calendar object.
From the Calendar implementation:
/**
* Value of the {#link #DAY_OF_WEEK} field indicating
* Monday.
*/
public final static int MONDAY = 2;

Related Links

What exactly are .jd files used for?
SerialPort.getCommPorts() does not return list of ttyS*
Send html email with java using html external template?
Where statements for many to many relations hibernate
Why implementation of Serializable interface is must in Entity,If an entity instance is passed by value as a detached object
Can you show me an example of using “System.gc()” to free the memory allocated by new Object in Java? [duplicate]
Android drawer layout not showing
Logging CXF rest service
Insert integers into 2d array
Why does setUseSystemMenuBar() get ignored when I have a SplashScreen-Image in my jar?
Incompatible Types: Cannot Cast View to CheckPreferenceBox
Using Future with ExecutorService
Java unhandled Exception
automated buttons implementation in java
Files are “open” in a List<File> and get out of memory
get the remaining length and quantity using java and sql server

Categories

HOME
vbscript
fft
grep
q
jsrender
rubygems
electronics
gps
disassembler
wamp
imacros
commonmark
windows-phone-7
event-handling
serverless-framework
uitypeeditor
angular-ui
swingx
autoconf
physics-engine
wkwebview
excel-2007
opennlp
selectedindexchanged
tooltipster
microsoft-chart-controls
react-chartjs
yadcf
twilio-api
.net-4.0
oracle-fusion-middleware
create-table
copying
asset-pipeline
rotational-matrices
http-referer
plsql-psp
file-format
retina-display
service-discovery
fedex
g-code
texmaker
ibpy
password-encryption
total-commander
s
angular2-meteor
apple-news
pango
yii2-extension
tactic
r-forge
mako
objective-c-swift-bridge
static-ip-address
transmitfile
google-web-starter-kit
connect-by
prettytensor
hexdump
ios4
xpath-1.0
photobucket
spim
endeca-workbench
coveralls
emailrelay
ionic
generic-programming
winddk
fpml
internet-connection
gnu-smalltalk
cdc
orchardcms-1.7
spring-validator
selected
gil
mercurial-server
gnu-prolog
xmlspy
w3wp.exe
blitz++
digest-authentication
web-application-design
infrastructure
vc90
ncqrs
webkit.net
libs
eqatec
port-number

Resources

Encrypt Message