Timestamp or date in Rust or Motoko

I’m using the Rust CDK, but this is relevant to Motoko as well. I want to generate a timestamp or get the current date and time…how do I do this? I did a quick skim through the Motoko documentation and didn’t see anything.

1 Like

Time.now() returns the canisters’ timestamp in nanoseconds

4 Likes

NB that timestamp seems to be static within the context of a message/request. So can’t use it to do any kind of timing within one such request.

2 Likes

That is what you’re going to have to go with because of the distributed nature of the calculation. If your output depends on the timing of internal processes you lose determinism due to different memory management, processing, etc. You’d never be able to reach consensus.

3 Likes

On second thought you could split the call into two functions where the second one is gated by a certain timestep. Microseconds is going to be tough though and you minimum unit is going to need to be blocks/second.

1 Like

Echoing the comments above. The timestamp is provided by the block maker and ratified by the notary group.

1 Like

Great information everyone, thanks. Does anyone have the Rust code to get the time?

1 Like
3 Likes

Here’s a hack to update the timestamp by await-ing:

actor Timer {
  func noop(): async () {};

  public func call(): async () {
    let a = Time.now();
    await noop();
    let b = Time.now();
  }
}
4 Likes

I believe this hack should be considered harmful. Why would someone use it?
I mean, one could just plus some value to the first timestamp.

Haha this really is a hack, it introduces the latency of another async call which could be several seconds. I guess if you’re doing really long synchronous operations and you need an updated timestamp, this could be useful…