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?
Asked
Active
Viewed 2.2k times
19
-
Related: How do you work with Date and time on Ethereum platform – Richard Horrocks Dec 01 '17 at 12:16
-
Related question for handling dates using solidity https://ethereum.stackexchange.com/questions/18192/how-do-you-work-with-date-and-time-on-ethereum-platform. Thank you – Kishore Dec 01 '17 at 09:23
1 Answers
21
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);
Victor Baranov
- 2,027
- 1
- 17
- 31
-
7Note that a getter
function birthdate() view returns uint256 { return birthdate;}is automatically added by its keywordpublic. – WBT Feb 02 '18 at 15:33