I know how to pass the current Unix time from the frontend:




let current_time = ctx.accounts.clock.unix_timestamp;

I do not want that. I need the smart contract itself to get the current time.

4 Answers 4


I'm assuming you're using anchor

let now_ts = Clock::get().unwrap().unix_timestamp;

You will need to pass in the system program account


Is this what you mean when you say "smart contract itself to get the current time"?

mod hello_anchor {
    use super::*;
    pub fn initialize(ctx: Context<Initialize>) -> Result<()> {
        let clock = Clock::get().unwrap();
        msg!("Timestamp: {}!", clock.unix_timestamp); // Message will show up in the tx logs

pub struct Initialize {}

The program log will look like this

enter image description here


What you have above is how the smart contract "itself" gets the current time.

When you add anchor.web3.SYSVAR_CLOCK_PUBKEY to your accounts, you're not passing in time from the frontend. You're simply specifying the public key of a system account that stores a cluster of on-chain data relating to time on Solana.

That account is verified by theclock: Sysvar<Clock, 'info> line in your validator and is the authority on handling time in Solana.

// pass this to Context
pub struct CreatePost<'info> {
    // add other properties
    pub post: Account<'info, PostAccount>,
    // Clock to save time of post
    pub clock: Sysvar<'info, Clock>,

PostAccount struct:

pub struct PostAccount {
    // add other properties

    // post time
    pub post_time: i64,

Define function in mod

pub fn create_post(ctx: Context<CreatePost>) -> ProgramResult {
     let post = &mut ctx.accounts.post;
     // get the timestamp of post
     post.post_time = ctx.accounts.clock.unix_timestamp;


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.