Reputation: 1
I'm working on Android project using Java and Android Studio IDE is warning me Date(int, int, int) is deprecated as of API16, but when I replace it to Calendar.set the build fails as non-static method cannot be referenced in a static context.
This method is being called on a date picker onItenSelectedListener that is static
How it can be deprecated if there is no replacement that can be really used?
Upvotes: 0
Views: 538
Reputation: 86379
Use LocalDate
from java.time, the modern Java date and time API. It’s much nicer to work with.
int year = 2019;
int month = 10;
int day = 15;
LocalDate date = LocalDate.of(year, month, day);
System.out.println(date);
The output from this snippet is:
2019-10-15
LocalDate
numbers both years and months the same way humans do, so there’s no subtracting funny values to adjust. If you need a Date
for an API not yet upgraded to java.time, the conversion goes like this:
Instant startOfDay = date.atStartOfDay(ZoneId.systemDefault()).toInstant();
Date oldfashionedDate = DateTimeUtils.toDate(startOfDay);
System.out.println(oldfashionedDate);
Tue Oct 15 00:00:00 CEST 2019
The classes Date
, Calendar
and GregorianCalendar
are all poorly designed and all long outdated. So do consider not using them.
java.time works nicely on both older and newer Android devices. It just requires at least Java 6.
Instant
to Date
use Date.from(startOfDay)
.org.threeten.bp
with subpackages.java.time
was first described.java.time
to Java 6 and 7 (ThreeTen for JSR-310).Upvotes: 1
Reputation: 1
I solved the problem replacing
return new Date(year-1900, month, day)
by
GregorianCalendar calendar = new GregorianCalendar(TimeZone.getTimeZone("GMT"));
calendar.set(year, month-1, day);
return calendar.getTime();
Upvotes: 0