如何显示区块链合约调用的时间



我想显示区块链合约调用的时间。

我目前正在使用这样的方法节省区块链中的时间

function userCheckIn(uint placeid) public {
    userCount++;
    checkins[userCount] = Checkin(placeid, msg.sender, now);
} 

但是,now像这样在前端显示随机数

1555650125
1555651118

你能给我任何建议吗?

提前非常感谢你。

时间戳看起来确实正确。在大多数编程语言和计算机系统中,时间存储为时间戳,时间戳存储在纪元(unix 时间戳(中。这些是大(长(数字,表示某个指定预定义时间的秒数。

若要将此纪元时间戳

转换为人类可读时间,可以使用在其构造函数中采用纪元时间戳的任何库。

// Create a new JavaScript Date object based on the timestamp
// multiplied by 1000 so that the argument is in milliseconds, not seconds.
var date = new Date(unix_timestamp*1000);
// Hours part from the timestamp
var hours = date.getHours();
// Minutes part from the timestamp
var minutes = "0" + date.getMinutes();
// Seconds part from the timestamp
var seconds = "0" + date.getSeconds();
// Will display time in 10:30:23 format
var formattedTime = hours + ':' + minutes.substr(-2) + ':' + seconds.substr(-2);

有关更多详细信息,请参阅此帖子。

这些不是随机数。这些是时间戳,它们表示自 1970 年 1 月 1 日以来经过的毫秒数。为了提取日期,您需要这样做:

function userCheckIn(uint placeid) public {
     userCount++;
     checkins[userCount] = Checkin(placeid, msg.sender, new Date(now) );
} 

由于now在前端为您提供有效的时间戳,因此new Date(now)可以轻松为您提供时间和日期。如果你想进一步细化这个日期,如月,天小时等,而不是使用默认的js方法,你可以查找momentJS库。

最新更新