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?

Bumblebee
  • 1,751
  • 3
  • 14
  • 23

1 Answers1

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