Working with dates and times
The module std::time
lets you work with the system time, and provides you with only the basic concepts of Instant
and Duration
(which we used in working with threads, see Chapter 9, Concurrency - Coding for Multicore Execution).
For any functionality beyond that, you need a crate. There are more than a dozen of them, with some specialized towards friendly output or games. The chrono
crate is the most popular, however, and provides you with the most functionality, for example dates and times, timezones, and a wealth of formatting possibilities. Consult the docs for a complete overview https://docs.rs/chrono/0.4.0/chrono/.
Let's use a simple example to write the current local time to a file, applying what we learned in the previous chapter.
Start your project with cargo new file_time --bin
.
In order to use the chrono
crate, edit the dependencies section of your Cargo.tml
to add this:
[dependencies] chrono = "0.4"
Add the following to your crate root (here main.rs
):
extern...