7 releases (1 stable)

1.0.0 Apr 5, 2024
0.6.0 Jul 25, 2023
0.4.1 May 25, 2022
0.3.0 Apr 11, 2022
0.1.0 Sep 10, 2021

#67 in Date and time

Download history 86/week @ 2023-12-22 138/week @ 2023-12-29 50/week @ 2024-01-05 43/week @ 2024-01-12 101/week @ 2024-01-19 105/week @ 2024-01-26 80/week @ 2024-02-02 33/week @ 2024-02-09 97/week @ 2024-02-16 107/week @ 2024-02-23 133/week @ 2024-03-01 92/week @ 2024-03-08 148/week @ 2024-03-15 63/week @ 2024-03-22 76/week @ 2024-03-29 277/week @ 2024-04-05

583 downloads per month
Used in 4 crates (2 directly)

MIT license

19KB
334 lines

unix-ts: Convertible Unix timestamps for Rust

ci codecov release docs

unix-ts is a library for dealing with timestamps. It supports lightweight creation and manipulation of timestamps.

The goal is to serve as a glue library that can take a timestamp and convert to whatever other formats are needed.

Usage

Add the crate to your Cargo.toml file like usual:

[dependencies]
unix-ts = "1"

You can create a timestamp with the ts! macro, which takes the Unix timestamp as an argument:

use unix_ts::ts;

// The argument is the number of seconds since the Unix epoch.
let t = ts!(1335020400);

// Fractional seconds are also allowed.
let t2 = ts!(1335020400.25);

For whole-second timestamps, you can also use the from method:

use unix_ts::Timestamp;

let t = Timestamp::from(1335020400);

For milliseconds, microseconds, or nanoseconds, there are specific from methods available:

use unix_ts::Timestamp;

let t = Timestamp::from_nanos(1335020400_000_000_000i64);

Finally, the new method accepts seconds and nanos. This is generally less convenient than the macro, though, because you have to convert fractional seconds to nanos by yourself.

Reading timestamps

There are three methods available for reading timestamps:

  • seconds() -> i64: Returns the whole seconds value of the timestamp.
  • at_precision(e) -> i128: Returns the timestamp as an integer at greater precision than the second. The e value represents the power of 10; therefore, at_precision(3) would return the value in milliseconds.
  • subsec(e) -> u32: Returns the subsecond value at the given precision. The e value represents the power of 10; therefore, subsec(3) would return the sub-second value in milliseconds.

Converting timestamps

Timestamps can currently be converted into integers (with the loss of the subsecond), or std::time::Duration. This is done by implementing the Rust From trait (so you can use the from or into methods).

Dependencies