I want to convert date to timestamp, my input is 26-02-2012
. I used
new Date(myDate).getTime();
It says NaN.. Can any one tell how to convert this?
I want to convert date to timestamp, my input is 26-02-2012
. I used
new Date(myDate).getTime();
It says NaN.. Can any one tell how to convert this?
Your string isn't in a format that the
Date
object is specified to handle. You'll have to parse it yourself, use a date parsing library like MomentJS or the older (and not currently maintained, as far as I can tell) DateJS, or massage it into the correct format (e.g.,2012-02-29
) before askingDate
to parse it.Why you're getting
NaN
: When you asknew Date(...)
to handle an invalid string, it returns aDate
object which is set to an invalid date (new Date("29-02-2012").toString()
returns"Invalid date"
). CallinggetTime()
on a date object in this state returnsNaN
.You need just to reverse your date digit and change
-
with,
:In your case:
P.S. UK locale does not matter here.
Try this function, it uses the Date.parse() method and doesn't require any custom logic:
Update:
DEMO (Tested in Chrome, FF, Opera, IE and Safari).