首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何不解析以数字作为日期的字符串?

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

Stack Overflow用户
提问于 2022-06-14 15:30:44
回答 1查看 37关注 0票数 0

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

代码语言:javascript
运行
复制
const value = new Date(input);
if (!(value instanceof Date && isFinite(value as unknown as number))) {
  return input;
}
// format date and return

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

EN

回答 1

Stack Overflow用户

发布于 2022-09-21 08:41:13

对解决方案并不那么满意,但到目前为止,效果还不错。

代码语言:javascript
运行
复制
transform(input: string) {
  if (!isNaN(input)) {
    return input;
  }
  
  if (input.replace(/[^0-9]/g, '').length < 6) {
    return input;
  }
  // format the date ...
}

对此进行测试:

代码语言:javascript
运行
复制
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');
});
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/72619680

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档