我想格式化一个日期字符串,但是对于所有其他字符串,只返回那个输入。现在,当输入是包含任意数字的字符串时。“您是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如何检查该字符串是否真的是包含数字或日期为字符串的字符串?输入日期字符串可能总是具有相同的模式,但理想情况下,它应该无关紧要。
发布于 2022-09-21 08:41:13
对解决方案并不那么满意,但到目前为止,效果还不错。
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');
});https://stackoverflow.com/questions/72619680
复制相似问题