Question

Can anybody help me with this, it's driving me crazy. I'm begginer with Javascript, and i encountered problem with dates for the first time now.

I have already asked this, but no one answered me: json with parsed time or timestamp to amchartss

Basically i have this XHR call.

 getJSON = function(url) {
    var xhr = new XMLHttpRequest();
    xhr.open('get', url, true);
    xhr.responseType = 'json';

    xhr.onload = function() {
        var status = xhr.status;
        if (status == 200) {
            chartLoad(xhr.response);
            console.log(xhr.response);
        } else {
            console.log("oh shit");
        }
    };
    xhr.send();
};

I'm getting in response here JSON file with timestamp, how can i convert all timestamps to date YYYY-MM-DD HH:mm.

Before instead of timestamps i had date string converted directly on server, in that way i didn't need to do converting on client side, but this way work only on Chrome.

HELP!

Était-ce utile?

La solution

Although there's no native date.format method in JavaScript you can grow your own for one off implementations. In your case something like:

var newDate = new Date(myTimeStamp);

var outDate = newDate.getFullYear()+"-"+(newDate.getMonth()+1)+"-"+newDate.getDate()+" "+newDate.getHours()+":"+newDate.getMinutes();

For todays date that will output: 2014-5-15 16:7 Note the +1 for getMonth which starts counting at 0 Might need an extra bit of fiddling if you want to ensure always two digits on values (ie leading zeros on single digits)

To do this within the xhr onload handler might be something like this:

           xhr.onload = function (e) {
                if (this.status == 200) {
                    var blob = this.response;

                    var img = document.createElement('img');
                    img.onload = function (e) {
                        window.URL.revokeObjectURL(img.src); // Clean up after yourself.
                    };
                    img.src = window.URL.createObjectURL(blob);
                    document.body.appendChild(img);

                    var myTimeStamp = e.timeStamp;
                    //I would probably want to put this date code
                    //in a separate function somewhere
                    var newDate = new Date(myTimeStamp);
                    var outDate = newDate.getFullYear()+"-"+(newDate.getMonth()+1)+"-"+newDate.getDate()+" "+newDate.getHours()+":"+newDate.getMinutes();
                    var div = document.createElement('div');
                    div.innerHTML = outDate;
                    document.body.appendChild(div);
                }
            };

Autres conseils

I like using moment.js for my datetime parsing and formatting needs:

http://momentjs.com/

Code ends up like this:

moment(some_timestamp).format('YYYY-MM-DD HH:mm')
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top