Search code examples
javascriptjsondatetimeodata

How to convert JSON (OData) time in something like gg-mm-aaaa in Javascript?


I've a JSON like this ...

{
"d": {
    "__count": "5798",
    "results": [{
        "time": "\/Date(1467039720000+0120)\/",
        "internalId": "5771271b84aed43d477c901b",
        "datasetVersion": 3,
        "idDataset": "1214",
    }, {
        "time": "\/Date(1467036120000+0120)\/",
        "internalId": "577118c784aed43d477bdf90",
        "datasetVersion": 3,
        "idDataset": "1215",
 .....

and I'd like to extract and convert the time in a format like gg-mm-aaaa using javascript (or PHP if necessary ...).

Note that I know that "+120" are minutes ... so 2 hours.

Is there any javascript library or code sample to make this transformation?


Solution

  • Try This

    function FormatDate(value) {
        var pattern = /Date\(([^)]+)\)/;
        var results = pattern.exec(value);
        var dt = new Date(parseFloat(results[1]));
        console.log(dt);
        console.log(dt.getMonth());
        console.log((dt.getMonth() + 1) + "/" + dt.getDate() + "/" + dt.getFullYear());
    }
    

    For example

    FormatDate("/Date(1467039720000+0120)/");
    

    Output:

    Mon Jun 27 2016 11:02:00 GMT-0400 (US Eastern Daylight Time)
    VM64:50 5
    VM64:51 6/27/2016
    

    Here is the fiddle link:

    https://jsfiddle.net/jkqm4ej3/