0

How to get a date from JDateChooser and format it?

JDateChooser instance

private void jDateChooser1PropertyChange(java.beans.PropertyChangeEvent evt) { 
   
   SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

   String date = sdf.format(jDateChooser1.getDate());
   System.out.println("date:"+ date);
   
}  

I am getting errors shown below

Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException: Cannot invoke 
"java.util.Date.getTime()" because "date" is null

at java.base/java.util.Calendar.setTime(Calendar.java:1801)
at java.base/java.text.SimpleDateFormat.format(SimpleDateFormat.java:975)
at java.base/java.text.SimpleDateFormat.format(SimpleDateFormat.java:968)
at java.base/java.text.DateFormat.format(DateFormat.java:375)
at com.mycompany.pos.add_stock_adjustment1.jDateChooser1PropertyChange(add_stock_adjustment1.java:880)
at com.mycompany.pos.add_stock_adjustment1$7.propertyChange(add_stock_adjustment1.java:466)
at java.desktop/java.beans.PropertyChangeSupport.fire(PropertyChangeSupport.java:341)
at java.desktop/java.beans.PropertyChangeSupport.firePropertyChange(PropertyChangeSupport.java:333)
at java.desktop/java.beans.PropertyChangeSupport.firePropertyChange(PropertyChangeSupport.java:266)    

How to fix this error?

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
  • The exception message is quite explanatory but without sharing the rest of your code, it would be hard to determine where exactly the error stems from. – akortex Sep 27 '21 at 06:56
  • But, If I am not formating it, I am getting the date which I have chosen. –  Sep 27 '21 at 06:59
  • Please include your whole code segment in order for someone to be able to help you. – akortex Sep 27 '21 at 07:03
  • I recommend you don’t use `SimpleDateFormat` and `Date`. Those classes are poorly designed and long outdated, the former in particular notoriously troublesome. Instead use `LocalDate` and `DateTimeFormatter`, both from [java.time, the modern Java date and time API](https://docs.oracle.com/javase/tutorial/datetime/). You should also be able to find a date picker that supports `LocalDate` rather than `Date` (or both). – Ole V.V. Sep 27 '21 at 20:03

1 Answers1

1
private void jDateChooser1PropertyChange(java.beans.PropertyChangeEvent evt) {                                             
   if ("date".equals(evt.getPropertyName())) { 
       SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
       String date = sdf.format(jDateChooser1.getDate());
       System.out.println("date:"+ date);
   }else{
       System.out.println("null");
   } 
} 

Now it's working.