Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
wants to merge 1 commit into
base: dev
Choose a base branch
from

Conversation

bylexus
Copy link

@bylexus bylexus commented Sep 6, 2022

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.

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:

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

you can now use the easier `formatIf()` function:

```js
let output = dayjs(someDateStr).formatIf('DD.MM.YYYY', '-');
```
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant