new Date(milliseconds) returns Invalid date

JavascriptDateTimeMilliseconds

Javascript Problem Overview


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?

Javascript Solutions


Solution 1 - Javascript

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)); 

Solution 2 - Javascript

The Date function is case-sensitive:

new Date(Milliseconds); 

Solution 3 - Javascript

instead of this

new date(Milliseconds); 

use this

new Date(Milliseconds); 

your statement will give you date is not defined error

Solution 4 - Javascript

I was getting this error due to a different reason.

I read a key from redis whose value is a json.

client.get(someid, function(error, somevalue){});

Now i was trying to access the fields inside somevalue (which is a string), like somevalue.start_time, without parsing to JSON object. This was returning "undefined" which if passed to Date constructor, new Date(somevalue.start_time) returns "Invalid date".

So first using JSON.parse(somevalue) to get JSON object before accessing fields inside the json solved the problem.

Solution 5 - Javascript

Is important to note that the timestamp parameter MUST be a number, it cannot be a string.

new Date(1631793000000).toLocaleString('en-GB', { timeZone: 'America/Argentina/Buenos_Aires' });

// Returns: '16/09/2021, 08:50:00'

new Date("1631793000000").toLocaleString('en-GB', { timeZone: 'America/Argentina/Buenos_Aires' });

// Returns: 'Invalid Date'

In case you're receiving the timestamp as string, you can simply wrap it around parseInt(): parseInt(your_ts_string)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser1634451View Question on Stackoverflow
Solution 1 - JavascriptapsillersView Answer on Stackoverflow
Solution 2 - Javascriptic3b3rgView Answer on Stackoverflow
Solution 3 - JavascriptSachinView Answer on Stackoverflow
Solution 4 - JavascriptVinay VemulaView Answer on Stackoverflow
Solution 5 - JavascriptJimmy AdaroView Answer on Stackoverflow