Categories
JavaScript Answers

How to validate a timestamp in JavaScript?

Spread the love

Sometimes, we want to validate a timestamp in JavaScript.

In this article, we’ll look at how to validate a timestamp in JavaScript.

How to validate a timestamp in JavaScript?

To validate a timestamp in JavaScript, we can call getTime on a Date instance and see if it returns a value greater than 0.

For instance, we write:

console.log(new Date('2012-08-09').getTime() > 0)
console.log(new Date('abc').getTime() > 0)

Then the first log will log true since it’s a valid date.

And the 2nd log will log true since it’s not a valid date.

getTime returns a timestamp in milliseconds.

Conclusion

To validate a timestamp in JavaScript, we can call getTime on a Date instance and see if it returns a value greater than 0.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *