迄今为止的Javascript时间戳 [英] Javascript timestamp to date
问题描述
有人可以帮助我吗,这让我发疯.我是Java语言的初学者,现在我第一次遇到日期问题.
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.
我已经问过这个,但是没有人回答我: 带有已解析的时间或时间戳的图表的json
I have already asked this, but no one answered me: json with parsed time or timestamp to amchartss
基本上我有这个XHR呼叫.
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();
};
我在这里得到带有时间戳的JSON文件作为响应,如何将所有时间戳转换为日期YYYY-MM-DD HH:mm.
I'm getting in response here JSON file with timestamp, how can i convert all timestamps to date YYYY-MM-DD HH:mm.
在此之前,我没有在服务器上直接转换日期字符串,而无需使用时间戳,因此我不需要在客户端进行转换,但是这种方式仅适用于Chrome.
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.
帮助!
推荐答案
尽管JavaScript中没有本地的date.format方法,但您可以自己开发一种实现.在您的情况下,例如:
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();
对于今天将输出的日期:2014-5-15 16:7
注意getMonth的+1
从0开始计数
如果您想确保值始终是两位数(例如,一位数的前导零),则可能需要多花点功夫
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)
要在xhr onload处理程序中执行此操作,可能是这样的:
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);
}
};
这篇关于迄今为止的Javascript时间戳的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!