时间戳错误处理

时间:2018-07-03 22:59:20

标签: javascript node.js

它将日期转换为时间戳:

let Record1 = { SubmitDate: "2012-03-24 17:45:12" }

try {
  timestamp = parseInt((new Date(Record1.SubmitDate).getTime() / 1000).toFixed(0));
} catch(err) {
  timestamp = null;
}

console.log(timestamp)

返回:1332611112

如果SubmitDate为null或SubmitDate属性不存在,则应返回null。由于某种原因,它没有执行到catch块中?

示例

let Record2 = { SubmitDate: null } 
let Record3 = { } 

我希望它们都返回null。时间戳记应有效,否则返回null。

该如何解决?

2 个答案:

答案 0 :(得分:2)

使用未定义或null参数调用new Date时,不会引发错误:

console.log(new Date(undefined).getTime());
console.log(new Date(null).getTime());

然后,用parseIntNaN调用0会得出0。

即使您可以使用try / catchtry / catch语句也有点昂贵:它们需要取消整个通话堆。只需使用条件运算符即可。也不需要parseInt,因为您已经在使用toFixed(0)

const getTimestamp = record => {
  const timestamp = new Date(record.SubmitDate).getTime();
  if (timestamp == 0 || Number.isNaN(timestamp)) return null;
  return (timestamp / 1000).toFixed(0);
};

console.log(getTimestamp({}));
console.log(getTimestamp({ SubmitDate: null }));
console.log(getTimestamp({ SubmitDate: "2012-03-24 17:45:12" }));
console.log(getTimestamp({ SubmitDate: "foo" }));

答案 1 :(得分:0)

请记住

parseInt((new Date(null).getTime() / 1000).toFixed(0))

将返回0

但是

parseInt((new Date(undefined).getTime() / 1000).toFixed(0))

将返回NaN

无论||会寻找布尔值并且强制转换为0,而“ NaN”将为false,所以

var timestamp = parseInt((new Date(record.SubmitDate).getTime()/1000).toFixed(0)) || null;
根据示例2018-22-22 44:88

,即使时间戳不正确,

也会为您解决问题