dayjs icon indicating copy to clipboard operation
dayjs copied to clipboard

[Plugin]: `formatIf`: like format(), but also works for invalid dates.

Open bylexus opened this issue 3 years ago • 0 comments

I created a small plugin, formatIf, to enhance the original format()'s behaviour for invalid dates: formatIf() returns the formatted date (wrapper around format()) if the dayjs object is valid. If not, a default / configurable response is returned.

The intention is to have a more handy dayjs().format() function, which also works for invalid dates. This is especially useful in contexts where you want to display a date in the frontend, and want a sensible output if the date is null/invalid.

Example:

Instead of writing:

let someDate = dayjs(someDateStr);
let output = someDate.isValid() ? someDate.format('DD.MM.YYYY') : '-';

you can now use the easier formatIf() function:

let output = dayjs(someDateStr).formatIf('DD.MM.YYYY', '-');

Please consider adding this plugin to the official plugins list. If you have any questions / caveats, please contact me.

bylexus avatar Sep 06 '22 09:09 bylexus