19

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?

2

1 Answer 1

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);
1
  • 7
    Note that a getter function birthdate() view returns uint256 { return birthdate;} is automatically added by its keyword public.
    – WBT
    Feb 2, 2018 at 15:33

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.