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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With