How to validate timestamp in javascript

The solution of @Jørgen is nice but if you have a date before January 1, 1970 your timestamp will be a negative number but also a valid timestamp.

function isValidTimestamp(_timestamp) {
    const newTimestamp = new Date(_timestamp).getTime();
    return isNumeric(newTimestamp);
}

function isNumeric(n) {
    return !isNaN(parseFloat(n)) && isFinite(n);
}

The numeric validation I took from the following SO answer.

For example:

isValidTimestamp('12/25/1965') // true

Every valid number is a timestamp. If it satisfies the condition of valid integer number then it will also satisfy the condition of the valid timestamp.

Timestamp = The number of milliseconds since 1970/01/01


var d = Date.parse(your_timestamp);

d should be a valid number and not NaN.

ref: http://www.w3schools.com/jsref/jsref_parse.asp


You can validate if a string is a valid timestamp like this:

var valid = (new Date(timestamp)).getTime() > 0;

var valid = (new Date('2012-08-09')).getTime() > 0; // true
var valid = (new Date('abc')).getTime() > 0; // false

Revisiting this answer after many years, validating dates can still be challenging. However, some of the argument is that the built in parser accepts a number of input format, many of which have little relevance.

The question here is to validate a timestamp of multiple formats, and unless the date parser can help you, there is a need to convert the timestamp into a generic format that is comparable. How to convert into this format depends on the format of the input, and in case of incompatible inputs, a tailored conversion algorithm will have to be developed.

Either use the built in date parser, as described above, otherwise, you will have to parse the input manually, and validate it accordingly.