简体   繁体   English

日期类将时间戳转换错误

[英]Date class converts Timestamp wrong

In my application, I am creating a live console where I output messages with their timestamp and contents. 在我的应用程序中,我正在创建一个实时控制台,在其中输出带有时间戳和内容的消息。 From what I read, the approach I am using below with the Date() class should work as expected, where the timestamp is multiplied by 1000 to get the milliseconds. 根据我的阅读,下面在Date()类中使用的方法应该可以按预期工作,其中将时间戳乘以1000以得到毫秒。

I am logging the timestamp for debugging purposes and getting values like "1441041070066". 我正在记录时间戳以进行调试,并获取诸如“ 1441041070066”的值。 When I plug these into the Epoch/Unix Converters, the date/time is correct. 当我将它们插入到Epoch / Unix转换器时,日期/时间是正确的。 My code however is giving my nonsense like "22:7:46" and then 1 minute later "20:48:37". 但是,我的代码却给我胡说八道,例如“ 22:7:46”,然后在1分钟后给出“ 20:48:37”。 Can anyone please explain what it is that I am doing wrong in this case? 有人可以解释在这种情况下我做错了什么吗?

messages.forEach( function (item)
{
    var timestamp = item.Timestamp; // /Date(1440823073243)/
    var timestamp = timestamp.substring(timestamp.lastIndexOf("(")+1, timestamp.lastIndexOf(")"));

    console.log(timestamp);

    var source = item.Source;
    var type = item.Type;
    var contents = item.Contents;

    // Get Date/Time in Milliseconds
    var date = new Date(timestamp * 1000);
    var time = date.getHours() + ":" + date.getMinutes() + ":" + date.getSeconds();

    console_log("<font color='blue'>" + time + "</font>" + ": " + contents);
});

The timestamp you've got is already in milliseconds. 您获得的时间戳已经毫秒为单位。 I don't know which converter you used, but if you put 1440823073243 into epochconverter.com it shows: 我不知道您使用了哪个转换器,但是如果您将1440823073243放入epochconverter.com,则会显示:

Assuming that this timestamp is in milliseconds 假设此时间戳以毫秒为单位

... and comes up with a timestamp of GMT: Sat, 29 Aug 2015 04:37:53 GMT . ...并带有GMT: Sat, 29 Aug 2015 04:37:53 GMT的时间戳GMT: Sat, 29 Aug 2015 04:37:53 GMT

So basically you should remove the * 1000 part of your code, but parse timestamp (which is still a string) into a number: 因此,基本上,您应该删除代码的* 1000部分,但是将timestamp (仍然是字符串)解析为数字:

var date = new Date(parseInt(timestamp));

Additionally, you should use alternative ways of formatting your date: 此外,您应该使用其他方式格式化日期:

  • You're currently using the users's time zone; 您当前正在使用用户的时区; it's not clear whether that's what you want or not. 尚不清楚这是否是您想要的。 (It may well be, but you should think about it.) (可能是,但是您应该考虑一下。)
  • By just using string concatenation, you won't get any padding, leading to strings like "22:7:46". 仅使用字符串连接,就不会得到任何填充,从而导致字符串类似“ 22:7:46”。

Basically, research alternative formatting options - whether as part of the Javascript standard libraries, or with something like moment.js . 基本上,研究替代格式设置选项-无论是作为Javascript标准库的一部分,还是诸如moment.js

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

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