Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to validate timestamp in javascript

How do you validate timestamp using javascript and timestamp to accept multiple formats e.g. YYYY-MM-DD HH:mm:ss.S, YYYY-MM-DD HH:mm:ss AM/PM.

like image 607
prashant Avatar asked Sep 14 '12 10:09

prashant


People also ask

How do you get a timestamp in JavaScript?

In JavaScript, in order to get the current timestamp, you can use Date. now() . It's important to note that Date. now() will return the number of milliseconds since January, 1 1970 UTC.


2 Answers

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.

like image 158
Jørgen Avatar answered Oct 10 '22 05:10

Jørgen


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
like image 9
Hristo Eftimov Avatar answered Oct 10 '22 05:10

Hristo Eftimov