Search code examples
javadateparsinggroovynullpointerexception

java.lang.NullPointerException: null while assigning current date to variable


In my ISData class i have create below method:

public static final DateFormat IN_DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd");

and now in my TSTIMP class i am trying to assign the current sys date value in the IN_DATE_FORMAT format to variable import_date which is Date datatype. But dont know how to do that. I want to parse this date into String as i need to later on store this in database table. Currently i am getting error as java.lang.NullPointerException: null

data.import_date = InstrumentMasterData.IN_DATE_FORMAT.parse(<need to provide sysdate> as String)

Below i tried for variable effective_date which is also Date datatype and it works fine:

data.effective_date = allocDate != null ? InstrumentMasterData.IN_DATE_FORMAT.parse(allocDate as String) : null

Also i have data.fund_quote_date variable which is also Date datatype and it should always be null. How can i assign null value to this varaible ?


Solution

  • i am trying to assign the current sys date value in the IN_DATE_FORMAT format to variable import_date which is Date datatype. But dont know how to do that.

    You can use DateFormat#format to get the system date string in the IN_DATE_FORMAT format e.g.

    data.import_date = InstrumentMasterData.IN_DATE_FORMAT.parse(InstrumentMasterData.IN_DATE_FORMAT.format(new Date()) as String)
    

    However, this is unnecessarily formatting a Date object using IN_DATE_FORMAT and then parsing the same formatted string back to a Date object. Instead of this, you can simply do:

    data.import_date = new Date();
    

    Also i have data.fund_quote_date variable which is also Date datatype and it should always be null. How can i assign null value to this varaible ?

    Simply, assign null to it:

    data.fund_quote_date = null;
    

    Note: If it is possible for you, stop using the outdated and error-prone java.util date-time API and SimpleDateFormat. Switch to the modern java.time date-time API and the corresponding formatting API (java.time.format). Learn more about the modern date-time API from Trail: Date Time.