Alexandre Muller
Alexandre Muller

Reputation: 1

Replace deprecated Java Date to Calendar.set ou GregorianCalendar.set in a static context

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

Answers (2)

Anonymous
Anonymous

Reputation: 86379

java.time and ThreeTenABP

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.

Question: Doesn’t java.time require Android API level 26?

java.time works nicely on both older and newer Android devices. It just requires at least Java 6.

  • In Java 8 and later and on newer Android devices (from API level 26) the modern API comes built-in. Only in this case for converting from Instant to Date use Date.from(startOfDay).
  • In non-Android Java 6 and 7 get the ThreeTen Backport, the backport of the modern classes (ThreeTen for JSR 310; see the links at the bottom).
  • On (older) Android use the Android edition of ThreeTen Backport. It’s called ThreeTenABP. And make sure you import the date and time classes from org.threeten.bp with subpackages.

Links

Upvotes: 1

Alexandre Muller
Alexandre Muller

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

Related Questions