Search code examples
grails-2.0gsp

GSP- formatDate tag issue handling null date


I used a collection of DATE field from Controller to GSP using the tag - But at times there are blanks and invalid data and it throws up an error. How should I handle this NULL pointer??

Code < g:formatDate format="yyyy-MM-dd" date="$ {objectInstance?.expiryDate} "/>

I also tried using this -- ${objectInstance?.expiryDate?.format("MM/dd/yyyy")} , but no luck. Thanks in Anticipation.


Solution

  • Vignesh,

    Here are a couple of potential solutions (assuming that you would be ok with showing nothing or some alternate text when the date is null):

    ${try{objectInstance?.expiryDate?.format('MM/dd/yyyy')}catch(e){''}}
    

    Or, you could handle this in the controller (my preferred method) using the same code as a above without the ${} wrapping it and set it into a model property.

    [expiryDateFormatted: try{objectInstance?.expiryDate?.format('MM/dd/yyyy')}catch(e){''}]
    

    Give those a try and see if they will work for you.

    After speaking with Vignesh it turns out that expiryDate is actually a string and not a date. Below is a solution that would work for a string value.

    ${try{new Date().parse('yyyy-MM-dd', objectInstance?.expiryDate).format('MM/dd/yyyy')}catch(e){''}}