Presenting Null DateTime Values in DB correctly

When creating pages using the scaffold option, and your schema contains a DateTime field type, a function that convert these date values to a more “usable” format:
const timeTag = (datetime) => {
return
<time dateTime={datetime} title={datetime}>
{new Date(datetime).toUTCString()}
</time>
}

If the value retrieved from the db is NULL, the date that will be presented is :1/1/1970 which is the first result of the new Date(null) function.
If you want to return a true null on the screen, change the function to:
const timeTag = (datetime) => {
return datetime ? (
<time dateTime={datetime} title={datetime}>
{new Date(datetime).toUTCString()}
</time>
) : null
}

If the returned value is null it will render NULL on the screen.

2 Likes

Thanks for posting these how-tos and snippets @wiezmankimchi They are really helpful and you’ve made them easily findable from search via specific Titles!

:tada:

With the PR that adds the other input types we could actually make this a <DatetimeLocalField> in the scaffold and you’d have a nice picker to set the date and time. If it’s NULL it just has placeholder values:

image

I added an issue to make this update! https://github.com/redwoodjs/redwood/issues/514

2 Likes