1

I would like to store a date and later on compare it to the current date.

How can I do it?

Thanks

1
  • Please clarify your specific problem or provide additional details to highlight exactly what you need. As it's currently written, it's hard to tell exactly what you're asking.
    – Community Bot
    Aug 26, 2022 at 15:06

1 Answer 1

3

It is not recommended to store and use dates on chain, since dates are not a native measurement of the blockchain.

Instead you can use the BlockNumber type, which is going to be a much better unit for time passing in your runtime logic.

Otherwise, if you are really insistent to use some kind of human date, you can use the Timestamp Pallet via the Time trait, which uses Moment type.

Both options would look something like this:

#![cfg_attr(not(feature = "std"), no_std)]

pub use pallet::*;

#[frame_support::pallet]
pub mod pallet {
    use frame_support::pallet_prelude::*;
    use frame_system::pallet_prelude::*;
    use frame_support::traits::Time;

    #[pallet::pallet]
    #[pallet::generate_store(pub(super) trait Store)]
    pub struct Pallet<T>(_);

    #[pallet::config]
    pub trait Config: frame_system::Config {
        type Time: Time;
    }

    type MomentOf<T> = <<T as Config>::Time as Time>::Moment;

    #[pallet::storage]
    pub type TimeStorage<T> = StorageValue<_, MomentOf<T>>;

    #[pallet::storage]
    pub type BlockNumberStorage<T: Config> = StorageValue<_, T::BlockNumber>;

    #[pallet::call]
    impl<T: Config> Pallet<T> {
        #[pallet::weight(0)]
        pub fn store_time(origin: OriginFor<T>) -> DispatchResult {
            let _who = ensure_signed(origin)?;
            let current_time = T::Time::now();
            TimeStorage::<T>::put(current_time);
            Ok(())
        }

        #[pallet::weight(0)]
        pub fn store_block_number(origin: OriginFor<T>) -> DispatchResult {
            let _who = ensure_signed(origin)?;
            let current_block_number = frame_system::Pallet::<T>::block_number();
            BlockNumberStorage::<T>::put(current_block_number);
            Ok(())
        }
    }
}
2
  • Let's assume I saved block number #25. How can I find in block #100 if my expiration date has expired or not?
    – P.E
    Aug 26, 2022 at 23:35
  • The point is that you make your expiration a # of blocks, not a date. You should generally be able to assume the block time of your chain is constant, for example on Polkadot it is 6 seconds. So if I want to make an expiration of 10 min, I would set the expiration blocks to 100 blocks. See this
    – Shawn Tabrizi
    Aug 27, 2022 at 15:31

Your Answer

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

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