eslint-plugin-unicorn icon indicating copy to clipboard operation
eslint-plugin-unicorn copied to clipboard

Rule proposal: `no-date-parsing`

Open axetroy opened this issue 1 year ago • 7 comments

Description

Date.parse does not behave consistently across platforms

There is already an existing plugin for this https://github.com/amzn/eslint-plugin-no-date-parsing

But it requires typescrpt parser and does not support eslint 9

Fail

new Date('2024-08-16');

Date.parse('2024-08-16')

Pass

import { parseISO } from 'date-fns';

// prefer `date-fns` or other Date library
const date = parseISO('2024-08-16');

Proposed rule name

no-date-parsing

Additional Info

No response

axetroy avatar Aug 24 '24 12:08 axetroy

Good idea, but I'm not sure if we can do it right without type information, we should only report strings.

fisker avatar Aug 24 '24 12:08 fisker

Ideally, it should be Temporal.PlainDate.from('2024-08-16');, but it's not available yet.

sindresorhus avatar Aug 24 '24 13:08 sindresorhus

You could consider to autofix for a YYYY-MM-DD string like so...

// Bad
new Date('2000-12-25');
// Good
Date.UTC(2000, 11, 25);

Rules of the game here https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date#date_time_string_format

geoffswift avatar Oct 19 '24 16:10 geoffswift

Date.UTC(2000, 11, 25);

This is bad in other ways. The fact that month is zero-indexed is a huge footgun.

sindresorhus avatar Jan 24 '25 08:01 sindresorhus

I think it's better to wait for Temporal. It's coming: https://developer.mozilla.org/en-US/blog/javascript-temporal-is-coming/

sindresorhus avatar Jan 24 '25 08:01 sindresorhus

Temporal is a good idea. Part of the point I was making is string literals can at least be handled, without worrying about type infererences. I think that's still sound at least.

geoffswift avatar Jan 26 '25 12:01 geoffswift

Since you mentioned Temporal, this issue would already be covered by https://github.com/sindresorhus/eslint-plugin-unicorn/issues/1315

fregante avatar Jan 29 '25 12:01 fregante