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.



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

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
var d = Date.parse(your_timestamp);

d should be a valid number and not NaN.



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


You can't generically parse a date string without knowing beforehand what the format is, or at least that it is one of a limited number of formats.

If the date component is always in ISO8601 format (yyyy-mm-dd) and the time is either 24hr or 12hr with AM or PM, you should be able to easily split off the time, look for AM or PM, then treat the time as 12 or 24hr depending on whether it's present or not.

Timezones must be specified as either UTC (Z) or hours +/-UTC, abbreviations such as EST are ambiguous (and not standardised).


by using new Date().getTime(); you can do this

and doing something like this

var getDate="12-12-2012";
var myDate=getDate.split("-");
var getDate=myDate[1]+"/"+myDate[0]+"/"+myDate[2];
alert(new Date(getDate).getTime());


Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.