To check if a given value is a valid Unix timestamp in JavaScript, you can use the Date
object and the getTime()
method. Here's an example:
function isUnixTimestamp(value) {
// Convert the value to a number
const timestamp = Number(value);
// Check if the converted timestamp is a valid number
if (Number.isNaN(timestamp)) {
return false;
}
// Create a new Date object using the timestamp
const date = new Date(timestamp * 1000);
// Check if the timestamp is valid by comparing the extracted time with the original timestamp
return date.getTime() === timestamp * 1000;
}
// Usage example
console.log(isUnixTimestamp(1621857900)); // Output: true
console.log(isUnixTimestamp(abc123)); // Output: false
console.log(isUnixTimestamp("1621857900")); // Output: true
console.log(isUnixTimestamp("abc123")); // Output: false
In this example, the isUnixTimestamp()
function takes a value and converts it to a number using Number(value)
. It then checks if the conversion results in a valid number. If not, it returns false
immediately.
If the conversion succeeds, it creates a new Date
object using the multiplied timestamp value (since JavaScript Date
objects work with milliseconds, while Unix timestamps are in seconds).
Finally, it compares the extracted time from the Date
object (date.getTime()
) with the original timestamp multiplied by 1000 to account for the difference in units. If they are equal, it means the original value was a valid Unix timestamp.
Note that this method assumes Unix timestamps are in seconds. If your timestamps are in milliseconds, you can remove the multiplication by 1000 in the code.
Comments
Post a Comment