如何不将数字作为日期的字符串解析?

发布于 2025-02-07 04:41:52 字数 347 浏览 2 评论 0原文

我想格式化一个日期字符串,但对于所有其他字符串,只需返回该输入即可。 现在,当输入是包含任何数字的字符串时,例如“您是数字1”时,字符串被解析为有效日期“ 2001年1月1日”。

const value = new Date(input);
if (!(value instanceof Date && isFinite(value as unknown as number))) {
  return input;
}
// format date and return

如何检查该字符串是否真的是仅包含数字或日期为字符串的字符串? 输入日期字符串可能始终具有相同的模式,但理想情况下,这无关紧要。

I want to format a date string but for all other strings just return that input.
Now when the input is a string that contains any number e.g. "You are number 1", the string is parsed as a valid date "1 Jan 2001".

const value = new Date(input);
if (!(value instanceof Date && isFinite(value as unknown as number))) {
  return input;
}
// format date and return

How can I check if that string is really a string containing just a number or a date as string?
The input date string might always have the same pattern but ideally it shouldn't matter.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

小红帽 2025-02-14 04:41:53

对解决方案并不满意,但到目前为止运行良好。

transform(input: string) {
  if (!isNaN(input)) {
    return input;
  }
  
  if (input.replace(/[^0-9]/g, '').length < 6) {
    return input;
  }
  // format the date ...
}

为此测试:

it('should ignore string and number values', () => {
  expect(pipe.transform('abc')).toBe('abc');
  expect(pipe.transform('This is not a date')).toBe('This is not a date');
  expect(pipe.transform('9999')).toBe('9999');
  expect(pipe.transform('000010')).toBe('000010');
  // will be parsed as a date
  expect(pipe.transform('Tue Sep 20 2022')).not.toBe('Tue Sep 20 2022');
});

Not that happy with the solution but it is working fine so far.

transform(input: string) {
  if (!isNaN(input)) {
    return input;
  }
  
  if (input.replace(/[^0-9]/g, '').length < 6) {
    return input;
  }
  // format the date ...
}

Test for that:

it('should ignore string and number values', () => {
  expect(pipe.transform('abc')).toBe('abc');
  expect(pipe.transform('This is not a date')).toBe('This is not a date');
  expect(pipe.transform('9999')).toBe('9999');
  expect(pipe.transform('000010')).toBe('000010');
  // will be parsed as a date
  expect(pipe.transform('Tue Sep 20 2022')).not.toBe('Tue Sep 20 2022');
});
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文