Javascript timestamp to date

雨燕双飞 提交于 2019-12-06 07:17:10

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

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')
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!