Null Safe Dates

classic Classic list List threaded Threaded
6 messages Options
Reply | Threaded
Open this post in threaded view
|

Null Safe Dates

bigal.nz
Hello,

I am trying to get a null safe date expression which would return '' instead of a null.

I have:

td th:text="${#dates.format(agencyComment.getCommentDate(), 'dd/MM/yy HH:mm')}">

I tried this where emptyDate is jus place holder textl

td th:text="${#dates.format(agencyComment.getCommentDate(), 'dd/MM/yy HH:mm')} ? : #{emptyDate}">

Whats the correct way please?
Reply | Threaded
Open this post in threaded view
|

Re: Null Safe Dates

danielfernandez
Administrator
I'm not sure what you mean. That expression in your first fragment will return null, and "th:text" works so that, when the result of evaluation is null, it outputs nothing:
<td></td>
So the result is 100% equivalent in this case to returning an empty string...

Reply | Threaded
Open this post in threaded view
|

Re: Null Safe Dates

bigal.nz
Well on load I get:

Error formatting date with format pattern "dd/MM/yy HH:mm" (newplan:237)

newPlan 237 is :

td th:text="${#dates.format(agencyComment.getCommentDate(), 'dd/MM/yy HH:mm')}">/td><input type="hidden" th:value="${#dates.format(agencyComment?.commentDate, 'dd/MM/yy HH:mm')}" th:name="plan.agencyComments[__${agencyCommentRow.index}__].commentDate"/>

its a object with a collection of dates some are null. The valid ones look like:

2017-06-13 05:33:04.0

So the logic I was attemping in my original post was to avoid the formatting error, which I presume was triggered because it tried to format a 'CommentDate' which was null?

The logic being if expression is not null then format.date.... else return empty string.

Al
Reply | Threaded
Open this post in threaded view
|

Re: Null Safe Dates

danielfernandez
Administrator
If the date passed to #dates.format(...) is null, then the result is null too, not an exception. So your null values are not the problem. Most probably it's the non-null values. Are you sure these are java.util.Date objects?
Reply | Threaded
Open this post in threaded view
|

Re: Null Safe Dates

bigal.nz
In reply to this post by bigal.nz
I saw your example on SO too:

https://stackoverflow.com/questions/13825570/thymeleaf-best-practice-for-checking-for-null-when-formatting-ie-dates

th:text="${agencyComment.commentDate} ? ${#dates.format(agencyComment.getCommentDate(), 'dd/MM/yy HH:mm')}"

SO I tried the above syntax - not joy either - same error.
Reply | Threaded
Open this post in threaded view
|

Re: Null Safe Dates

bigal.nz
This post was updated on .
In reply to this post by danielfernandez


There is that date and two nulls.