-2

I want to format a date, using

DateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
return dateFormat.format(LocalDateTime.now().plusMinutes(10));

but I have the error:

java.lang.IllegalArgumentException: Cannot format given Object as a Date
Sandro Rey
  • 1,473
  • 10
  • 24
  • 63

3 Answers3

0

There are two different methods of dealing with dates in Java. DateFormat is for the old, not-to-be-used java.util.Date package. Your LocalDateTime is from the much better java.time package, and needs to use a DateTimeFormatter:

DateTimeFormatter format = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");
return format.format(LocalDateTime.now().plusMinutes(10));
squaregoldfish
  • 638
  • 9
  • 20
0

you would need to use DateTimeFormatter instead of DateFormatter as the object you are trying to format is LocalDateTime.

broken98
  • 43
  • 6
0

Do not use outdated Date/Time formatter, DateFormat. Use a modern Date/Time formatter, DateTimeFormatter instead.

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

public class Main {
    public static void main(String[] args) {
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");
        System.out.println(formatter.format(LocalDateTime.now().plusMinutes(10)));
    }
}

Output:

20200415203347
halfer
  • 19,471
  • 17
  • 87
  • 173
Arvind Kumar Avinash
  • 62,771
  • 5
  • 54
  • 92