-2

I want to format a LocalDateTime using the following code:

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
Arvind Kumar Avinash
  • 71,965
  • 6
  • 74
  • 110
Sandro Rey
  • 2,429
  • 13
  • 36
  • 80

3 Answers3

1

You can not format the java.time types using the legacy formatting type, java.text.DateFormat. Use java.time.format.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

Note that the java.time API, released with Java-8 in March 2014, supplanted the error-prone legacy date-time API. Since then, using this modern date-time API has been strongly recommended. Learn more about the modern Date-Time API from Trail: Date Time.

Arvind Kumar Avinash
  • 71,965
  • 6
  • 74
  • 110
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
  • 709
  • 8
  • 20
0

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

broken98
  • 43
  • 6