Search code examples
reactjsethereumsolidity

How to show the time when the blockchain contract called?


I want to show the time when blockchain contract called.

I am currently saving the time in the blockchain using a method like this

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

However, now shows random number in frontend like this

1555650125
1555651118

Could you give me any advise, please?

Thank you so much in advance.


Solution

  • The timestamp does seem right. In most of the programming languages and computer systems, time is stored as a timestamp, which is stored in epoch (unix timestamp). These are big(long) numbers which represent the seconds from some specified predefined time.

    To convert this epoch timestamp to a human readable time, you can use any library that takes in epoch timestamp in its constructor.

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

    Refer to this post for more details.