简体   繁体   English

时间戳中的错误日期

[英]Wrong date from timestamp

I have a problem which can't solve by myself.我有一个自己无法解决的问题。

Here is timestamp 1308085200 taken from my website database.这是从我的网站数据库中获取的时间戳 1308085200。 It represents 2011-06-15 12:00:00它代表 2011-06-15 12:00:00

Here is javascript code which I use to "fetch" date in human readable format.这是 javascript 代码,我用它来“获取”人类可读格式的日期。

var date    = new Date(1308085200 * 1000);
var year    = date.getFullYear();
var month   = date.getMonth();
var day     = date.getDate();
var hour    = date.getUTCHours();
var minute  = date.getUTCMinutes();
var seconds = date.getUTCSeconds();

The problem is that I get wrong results.问题是我得到错误的结果。 For example the code above shows 2011-5-15 21:0:0 instead of 2011-06-15 12:00:00例如上面的代码显示 2011-5-15 21:0:0 而不是 2011-06-15 12:00:00

What I do wrong and how to fix that?我做错了什么以及如何解决?

JavaScript's Date::getMonth() returns a zero-based integer from 0 to 11 which is why your date is showing May instead of June. JavaScript 的Date::getMonth()从 0 到 11 返回从零开始的 integer,这就是为什么您的日期显示为 5 月而不是 6 月的原因。

https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Date/getMonth https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Date/getMonth

Update更新

As for the time portion, this is what I get (AEST)至于时间部分,这就是我得到的(AEST)

var d = new Date(1308085200000); // Wed Jun 15 07:00:00 GMT+1000 (EST)
d.toUTCString() // Tue, 14 Jun 2011 21:00:00 GMT
d.getUTCFullYear() // 2011
d.getUTCMonth() // 5
d.getUTCDate() // 14
d.getUTCHours() // 21
d.getUTCMinutes() // 0
d.getUTCSeconds() // 0

Looks like your timestamp is actually not what you think it is.看起来你的时间戳实际上不是你想象的那样。

Well, JavaScript's getMonth() function sucks and starts with 0 for January.好吧,JavaScript 的 getMonth() function 很烂,一月份从 0 开始。 You have to add one.你必须添加一个。

Maybe you want to use date js , since it fixes some of these problems.也许您想使用date js ,因为它解决了其中一些问题。

The date and time can vary dependent on the timezone you're in. That's why in my zone (GMT+2000) new Date(1308085200*1000) displays Tue Jun 14 2011 23:00:00 GMT+0200 (W. Europe Daylight Time) .日期和时间可能因您所在的时区而异。这就是为什么在我的区域 (GMT+2000) new Date(1308085200*1000)显示Tue Jun 14 2011 23:00:00 GMT+0200 (W. Europe Daylight )时间) Check this reference for everything you always wanted to know about dates in javascript查看此参考资料,了解您一直想了解的有关 javascript 中日期的所有信息

Regarding formatting (leading zero's etc.), maybe this jsfiddle can help you?关于格式(前导零等),也许这个 jsfiddle可以帮助你?

Try this:尝试这个:

 function timeConverter(createdAt) {
  var date = new Date(createdAt);
  date.toUTCString()
  var year = date.getUTCFullYear();
  var month = date.getUTCMonth()+1;
  var day = date.getUTCDate();
  return day+"-"+month+"-"+year;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM