Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

new Date(milliseconds) returns Invalid date

I am trying to convert milliseconds to a date using the javascript using:

new Date(Milliseconds);  

constructor, but when I give it a milliseconds value of say 1372439683000 it returns invalid date. If I go to a site that converts milliseconds to date it returns the correct date.

Any ideas why?

like image 980
user1634451 Avatar asked Jun 28 '13 18:06

user1634451


People also ask

Why does JavaScript show invalid date?

The JavaScript exception "invalid date" occurs when a string leading to an invalid date has been provided to Date or Date. parse() .

How do you convert milliseconds to date format?

Converting Milliseconds to Date For the current millisecond, use the function getTime() which is used in JavaScript to return the number of milliseconds from the standard date “January 1, 1970, 00:00:00 UTC” till the current date as shown below: var checkTime = new Date().

How do I check if a date is valid?

If the variables are of Date object type, we will check whether the getTime() method for the date variable returns a number or not. The getTime() method returns the total number of milliseconds since 1, Jan 1970. If it doesn't return the number, it means the date is not valid.

How do you fix invalid time value RangeError?

The "Uncaught RangeError: Invalid time value" error occurs when calling a method on an invalid date, e.g. new Date('asdf'). toISOString() . To solve the error, conditionally check if the date is valid before calling the method on it.


1 Answers

You're not using a number, you're using a string that looks like a number. According to MDN, when you pass a string into Date, it expects

a format recognized by the parse method (IETF-compliant RFC 2822 timestamps).

An example of such a string is "December 17, 1995 03:24:00", but you're passing in a string that looks like "1372439683000", which is not able to be parsed.

Convert Milliseconds to a number using parseInt, or a unary +:

new Date(+Milliseconds);  new Date(parseInt(Milliseconds,10));  
like image 73
apsillers Avatar answered Sep 16 '22 15:09

apsillers