Reputation: 10828
It convert date to timestamp:
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)
Return: 1332611112
If SubmitDate
is null or SubmitDate
property does not exist, it should return null. For some reason it doesn't execute into catch block?
Example
let Record2 = { SubmitDate: null }
let Record3 = { }
I would like both of them to return null. Timestamp should be valid otherwise return null.
How to fix this?
Upvotes: 0
Views: 761
Reputation: 370839
When new Date
is called with an undefined or null argument, it doesn't throw an error:
console.log(new Date(undefined).getTime());
console.log(new Date(null).getTime());
Then, calling parseInt
with either NaN
or 0
results in 0.
Even if you could use try
/ catch
, try
/ catch
statements are a bit expensive: they require unwinding the entire call stack. Just Use the conditional operator instead. There's also no need for parseInt
because you're already using 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" }));
Upvotes: 2
Reputation: 3917
keep in mind that
parseInt((new Date(null).getTime() / 1000).toFixed(0))
will return 0
but
parseInt((new Date(undefined).getTime() / 1000).toFixed(0))
will return NaN
no matter of that ||
will look for a boolean and cast of 0 and 'NaN' will be false so
var timestamp = parseInt((new Date(record.SubmitDate).getTime()/1000).toFixed(0)) || null;
will do the trick for you even in case of incorrect time stamp as per example 2018-22-22 44:88
Upvotes: 0