How do I pass a long number through javascript?

I want to convert Long date number from mongo db database to dd / mm / yyyy format in javascript.

When I put in a direct encoded value, like the following code, it gives the correct result:

function getDateIfDate(d) {
    var m = d.match(/\/Date\((\d+)\)\//);
    return m ? (new Date(+m[1])).toLocaleDateString('en-US', {month: '2-digit', day: '2-digit', year: 'numeric'}) : d;
}

console.log(getDateIfDate("/Date(1460008501597)/"));

      

Here is my code:

for(var i=0;i<keys;i++)
                {
                var tr="<tr>";
                tr+= "<td><input type='checkbox' name='record'></td>"
                tr+="<td>"+positionList[i]["fromDate"]+"</td>";
                var j = (positionList[i]["fromDate"]);
                console.log("value of j is =========="+j);
                console.log(getDateIfDate("/Date(j)/")); // actual conversion should happen here
}

      

What changes should I make to my code to get the date in the required format?

+3


source to share


3 answers


tr+="<td>"+positionList[i][new Date("fromDate").toLocaleString()]+"</td>";

      



try to replace the old line with this new one

+3


source


You can use momentjs for your case. It's very easy to use, if you want to format the date to DD / MM / YYYY , just add the following line:



var formattedDate = moment(new Date()).format("DD/MM/YYYY");

      

+2


source


You should call a function like this getDateIfDate("/Date("+j+")/");

instead getDateIfDate("/Date(j)/")

it means you are passing in a string "/Date(j)/"

.

 
function getDateIfDate(d) {
    var m = d.match(/\/Date\((\d+)\)\//);
    return m ? (new Date(+m[1])).toLocaleDateString('en-US', {month: '2-digit', day: '2-digit', year: 'numeric'}) : d;
}


var j= 1460008501597;

console.log(getDateIfDate("/Date("+j+")/"));
      

Run codeHide result


+2


source







All Articles