Convert milliseconds string to date in javascript

4.9k Views Asked by At

There were a lot of answered questions about converting milliseconds to date format but none of them was able to solve my problem.

I have a string (and not a time) coming in my javascript code. It is of the format as below

1380549600000+1000

When I try to parse it using the following code it gives me "invalid date" error.

My main objective is to convert this string to dd/mm/yyyy format. So was thinking of converting it into date and applying methods like "getMonth", etc

<script>
    var modDate = "1380549600000+1000"; //Note the value is in "" hence a string
    var d = new Date(modDate); //Invalid date error here
    document.getElementById("demo").innerHTML = d;
</script>

The following works just fine. But this is not the format I am getting.

<script>
    var modDate = 1380549600000+1000; //Note the value is no longer in ""
    var d = new Date(modDate); //No problems here
    document.getElementById("demo").innerHTML = d;
</script>

Please help. Thanks in advance.

Cheers.

4

There are 4 best solutions below

17
On BEST ANSWER

edit:-

eval is not the best approach, it is not safe to use eval, so use this instead:-

var modDate = "1380549600000+1000"
var temp = modDate.split("+");
modDate = parseInt(temp[0]) + parseInt(temp[1]);

I am not sure if you need that added 1000, if you don't, it could be done in one line as :-

modDate = parseInt(modDate.split("+")[0])

older approach :-

<script>
var modDate = eval("1380549600000+1000"); //Note the value is in "" hence a string
var d = new Date(modDate); //Invalid date error here
document.getElementById("demo").innerHTML = d;
</script>
8
On

Use parseInt to get the numeric value of the string (safer than eval, but same premise):

modDate = (isNaN(modDate)) ? parseInt(modDate, 10) : modDate;

if !isNaN(modDate) {
    var d = new Date(modDate);
    document.getElementById("demo").innerHTML = d;
} else {
    console.log("Value in modDate not a number");
}
0
On

Other approach w/o using eval:

var modDate = "1380549600000+1000";
var d = new Date(modDate.split("+")
    .map(parseFloat)
    .reduce(function(a,b){return a + b;}));
0
On

I had to use a bit of a mishmash of the answers here to get mine to work. My Date value was being sent to my web page as a String, like so: "/Date(978278400000-0500)/"

So I parsed it like this, to get it to display as a valid date:

// sDateString = "/Date(978278400000-0500)/";
 var modDate = sDateString.replace(/[\/Date\(\)]/g, "");
 return new Date(parseInt(modDate, 10));
//returns: Sun Dec 31 2000 11:00:00 GMT-0500 (Eastern Standard Time) {}