Let's say I want to store a birth date in in a solidity contract. Which data type do I have to use in the solidity contract? How do I write the date with web3 to the contract and how do I retrieve it from the contract in a human readable format?
1 Answer
In Solidity you will store date as uint
type
pragma solidity ^0.5.11;
contract BirthDate {
uint256 public birthdate;
function set(uint256 _birthdate) public {
birthdate = _birthdate;
}
function get() public view returns (uint _birthdate) {
return birthdate;
}
}
To set date in smart-contract with web3.js:
let date = (new Date()).getTime();
let birthDateInUnixTimestamp = date / 1000;
await BirthDate.methods.set(birthDateInUnixTimestamp).send(opts);
To get date from smart-contract with web3.js:
let birthDateInUnixTimestamp = await BirthDate.methods.get().call();
let date = new Date(birthDateInUnixTimestamp * 1000);
-
7Note that a getter
function birthdate() view returns uint256 { return birthdate;}
is automatically added by its keywordpublic
.– WBTFeb 2, 2018 at 15:33