Formatting datetime in Retool with JS - How to return "undefined" if SQL query returns blank

Im using the below JS to format my SQL's datetime to just show hh:mm. When there is no entries returned on my SQL query the below does not revert "undefined", it shows the current time. How do i stop it showing the current time or better still is there a more correct way to format datetime from SQL into Retool's JS.

{{moment(MechanicOffSite.data.DateTimeEntry['0']).format('hh:mm')}}

Use a ternary operator

For example if the SQL returns no entries you can do the following:

{{MechanicOffSite.data.DateTimeEntry['0'] != ''?moment(MechanicOffSite.data.DateTimeEntry['0']).format('hh:mm'):''}}

or if you need to specifically handle undefined as a value from the query
{{MechanicOffSite.data.DateTimeEntry['0'] != undefined?moment(MechanicOffSite.data.DateTimeEntry['0']).format('hh:mm'):''}}

1 Like

So by saying "!= undefined" is it saying return "undefined" if the query returns nothing?

Also just to confirm am I correct in how I formatted the datetime to just time (using moment) or is there a better way of doing it? Obviously it works but I just want to confirm best practice

You're testing to see if nothing comes back and if nothing comes back don't display anything. Looks like moment is correct and yes that is usually best practice IMO

Awesome, thanks for your input

I've tested this just now,

The below still returns the "now" time.
{{MechanicOffSite.data.DateTimeEntry['0'] != ''?moment(MechanicOffSite.data.DateTimeEntry['0']).format('hh:mm'):''}}

But this one seems to work fine.
{{MechanicOffSite.data.DateTimeEntry['0'] != undefined?moment(MechanicOffSite.data.DateTimeEntry['0']).format('hh:mm'):''}}

1 Like