0

I have a given task but don't really understand what to perform in this function. Here is the given code:

// Returns a Date value that is num days after current Date
public Date daysAfter(int num) {
    return null;
} 
Mureinik
  • 297,002
  • 52
  • 306
  • 350

2 Answers2

2

The easiest approach, IMHO, would be to use a Calendar object:

public static Date daysAfter(int num) {
    Calendar cal = Calendar.getInstance();
    cal.add(Calendar.DATE, num);
    return cal.getTime();
}
Mureinik
  • 297,002
  • 52
  • 306
  • 350
  • Thanks for the help. Can you also tell me about implementation of daysBefore() function? –  Nov 12 '18 at 06:41
  • @JustGamingJG just multiply `num` by `-1`. – Mureinik Nov 12 '18 at 06:50
  • I beg to differ. Compare to [the answer by Raheela Aslam](https://stackoverflow.com/a/53257014/5772882). That answer is easier. And clearer to read and more modern. The `Calendar` class has design issues and is long outdated. – Ole V.V. Nov 12 '18 at 07:25
  • 1
    FYI, the terribly troublesome old date-time classes such as [`java.util.Date`](https://docs.oracle.com/javase/10/docs/api/java/util/Date.html), [`java.util.Calendar`](https://docs.oracle.com/javase/10/docs/api/java/util/Calendar.html), and `java.text.SimpleDateFormat` are now [legacy](https://en.wikipedia.org/wiki/Legacy_system), supplanted by the [*java.time*](https://docs.oracle.com/javase/10/docs/api/java/time/package-summary.html) classes built into Java 8 and later. See [*Tutorial* by Oracle](https://docs.oracle.com/javase/tutorial/datetime/TOC.html). – Basil Bourque Nov 12 '18 at 21:41
2

You can get date plus your provided day as below:

public static LocalDate getDateAfter(Integer days) {
    return LocalDate.now().plusDays(days);
}
Raheela Aslam
  • 452
  • 2
  • 13