Is there a way to pull sec / nanosec out of std::time::Instant?

There is duration, but it measures diff of two Instants. I just want the sec/nanosec of Instant, from some common Epoc.

1 Like

There's no predefined common epoch for Instant in most systems. But you can make your own one instead.

static EPOCH: Lazy<Instant> = Lazy::new(|| Instant::now());
4 Likes

I was under the impression (perhaps incorrect) that

January 1, 1970 (midnight UTC/GMT)

was universally accepted ?

What bettter method for informing yourself of the usage of an API than reading the documentation? It explicitly says:

Instants are opaque types that can only be compared to one another. There is no method to get “the number of seconds” from an instant. Instead, it only allows measuring the duration between two instants (or comparing two instants).

So no, there's no epoch. (Unix epoch is also not as universally accepted as you think. Some APIs count from 1 Jan 2000, for example.)

If you need to work with wall clock time, then you don't want std::time::Instant. Instead, you want chrono::DateTime with an appropriate explicit time zone.

3 Likes

Instant uses whatever platform API provides a monotonic, high-resolution clock. Even on Unix systems, such clocks don't have a defined epoch. For example, as the documentation states, on Linux and BSDs clock_gettime with CLOCK_MONOTONIC is used, and its documentation says

CLOCK_MONOTONIC
Clock that cannot be set and represents monotonic time since some unspecified starting point.

A monotonic clock must by definition be detached from the system time, aka "wallclock time". System time may jump either forward or backward in a manner impossible to predict by the program; a monotonic clock cannot jump backward, which is reflected in the fact that a Duration can only be nonnegative.

5 Likes

You can do that for SystemTime, but not for Instant. There are many reasons for this, for example:

  1. If an Instant happened two minutes ago and you change the system clock, then the Instant will still have happened two minutes ago. It doesn't move together with the system clock.
  2. On some operating systems (but not all), the clock that the Instant uses will pause if the system goes to sleep. This means that two Instants can be a minute apart, even though the system clock when they were captured actually differ by several hours.

Because of these issues, it is not possible to compute the number of seconds since the unix epoch given just an Instant. It simply does not contain enough information to perform that computation. You would need to have captured a SystemTime at the same time as you captured the Instant to do that.

13 Likes

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.