0

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.

Dblaze47
  • 868
  • 5
  • 17
gnxvw
  • 404
  • 1
  • 9
  • 23

2 Answers2

2

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.

Dblaze47
  • 868
  • 5
  • 17
segfault
  • 504
  • 2
  • 6
0

Those are not random numbers. Those are timestamps, and they represent the milliseconds that has passed since Jan 1, 1970. In order to extract the date, you need to this:

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

Since now is giving you valid timestamps on frontend, new Date(now) will easily give you the time and date. If you want to further refine this date as per months, day hours etc. instead of using the default js methods you can look up momentJS library.

Dblaze47
  • 868
  • 5
  • 17
  • I wrote this function in Solidity file, so it says `Date` is `not found or not unique.` – gnxvw Apr 19 '19 at 05:48
  • 2
    I think you need to multiply the timestamp in seconds to milliseconds. try `new Date(now*1000)` – segfault Apr 19 '19 at 05:53
  • 1
    The JS Date should be available for Solidity. Try `new Date(now * 1000)`. And on that note, please post your question here as well for a specific Ethereum audience: https://ethereum.stackexchange.com/ . – Dblaze47 Apr 19 '19 at 05:54
  • @Dblaze47 `new Date(now*1000)` shows same error. Sure, thank you for your information. – gnxvw Apr 19 '19 at 07:20