I am trying to get a date of a certain format:

String pattern = "dd.MM.yyyy"; SimpleDateFormat formatter = new SimpleDateFormat(pattern); formatter.format(department.getStartDate()); 

The program fails with the error:

 Exception in thread "main" java.lang.NullPointerException at java.util.Calendar.setTime(Calendar.java:1770) at java.text.SimpleDateFormat.format(SimpleDateFormat.java:943) at java.text.SimpleDateFormat.format(SimpleDateFormat.java:936) at java.text.DateFormat.format(DateFormat.java:345) at CSV.Export.generateCSV(Export.java:49) at Main.main(Main.java:17) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:498) at com.intellij.rt.execution.application.AppMain.main(AppMain.java:144) 

StartDate is Date type:

 package Entity; import lombok.Getter; import lombok.Setter; import java.util.Date; public class Department { @Getter @Setter private Date startDate; } 

What could be the problem?

  • four
    The startDate value startDate be null . Did you check it? - Regent

1 answer 1

the error is that department.getStartDate() returns null .

Here is the code

 String pattern = "dd.MM.yyyy"; SimpleDateFormat formatter = new SimpleDateFormat(pattern); formatter.format(null); 

give the following result

 Exception in thread "main" java.lang.NullPointerException at java.util.Calendar.setTime(Calendar.java:1770) at java.text.SimpleDateFormat.format(SimpleDateFormat.java:943) at java.text.SimpleDateFormat.format(SimpleDateFormat.java:936) at java.text.DateFormat.format(DateFormat.java:345) 

As you can see, the exception matches yours.