1

Deprecated code, how to replace setDate and getDate, right now code works, but I can’t present it like that. I have tried Calendar, and I don’t see how that works. Code point is to move exact amount of days back in my calendar.

public void minusDay() {
    int days = dateRange();
    toDate.setDate(toDate.getDate()-days);   
k87
  • 11
  • 3
  • 2
    "Right now code works". Then don't touch it. – Kayaman Oct 24 '19 at 07:34
  • Do you talk about `java.util.Date`? – Sockenpuppe Oct 24 '19 at 07:34
  • Yes, it is java.util.Date. – k87 Oct 24 '19 at 07:39
  • 2
    *assuming* it is `java.util.Date`(there are more than 10 `setDate()` methods in Java SE), the [documentation](https://docs.oracle.com/en/java/javase/13/docs/api/java.base/java/util/Date.html#setDate(int)) says: "**Deprecated.** As of JDK version 1.1, replaced by Calendar.set(Calendar.DAY_OF_MONTH, int date)." (most deprecated methods/fields have a message with an alternative) – user85421 Oct 24 '19 at 07:40
  • You either don't touch your working code or you switch it entirely to using `java.time` instead of `java.util`. – deHaar Oct 24 '19 at 07:41
  • Possible duplicate of [How to replace getDate() from the type Date which is deprecated?](https://stackoverflow.com/questions/32694110/how-to-replace-getdate-from-the-type-date-which-is-deprecated) – Ashutosh Oct 24 '19 at 07:47
  • 1
    `setTime`? [deHaar](https://stackoverflow.com/questions/58536328/how-to-replace-setdate-and-getdate#comment103395477_58536328) means the [`java.base/java.time`](https://docs.oracle.com/en/java/javase/13/docs/api/java.base/java/time/package-summary.html) package - "The main API for **dates**, times, instants, and durations." - and its classes (the not-so-new API to be used instead of `Date`, `Calendar`, ...) – user85421 Oct 24 '19 at 07:50

1 Answers1

0

Java 8 Date API supports minusDays and plusDays methods on LocalDateTime instances.

If you don't want to convert your whole system using the Java 8 Date API, then you can just convert your Date object into LocalDateTime and work on it. You will also need to use ZonedDateTime to take into consideration the timezone also for the conversion.

public void minusDay() {
    int days = dateRange();
    LocalDateTime ldt = LocalDateTime.ofInstant(toDate.toInstant(), ZoneId.systemDefault());
    ldt.minusDays(days);
    ZonedDateTime zdt = ldt.atZone(ZoneId.systemDefault());
    toDate = Date.from(zdt.toInstant());
}

Source here.

sanastasiadis
  • 1,182
  • 1
  • 15
  • 23