There is duration, but it measures diff of two Instants. I just want the sec/nanosec of Instant, from some common Epoc.
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());
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.
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.
You can do that for SystemTime
, but not for Instant
. There are many reasons for this, for example:
- If an
Instant
happened two minutes ago and you change the system clock, then theInstant
will still have happened two minutes ago. It doesn't move together with the system clock. - On some operating systems (but not all), the clock that the
Instant
uses will pause if the system goes to sleep. This means that twoInstant
s 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.
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.