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 crate chrono; use chrono::prelude::*;
Replace the code in main.rs with this:
let local: DateTime<Local> = Local::now(); println!("{}", local);
Then test this by giving the command cargo run in the file_time folder, which will download chrono, install and compile it, and then compile and run the file_time app. This provides the local time, for example:
2017-08-17 10:41:40.539165700 +02:00
We now format this to a somewhat prettier output such as Thu, Aug 17 2017 10:41:40 AM, and write it to a log.txt file with the log_info function. Here is the complete code of main.rs:
extern crate chrono; use chrono::prelude::*; use std::io::prelude::*; use std::fs::File; use std::io; fn main() { let local: DateTime<Local> = Local::now(); let formatted = local.format("%a, %b %d %Y %I:%M:%S %p\n").to_string(); match log_info("log.txt", &formatted) { Ok(_) => println!("Time is written to file!"), Err(_) => println!("Error: could not create file.") } } fn log_info(filename: &str, string: &str) -> io::Result<()> { let mut f = try!(File::create(filename)); try!(f.write_all(string.as_bytes())); Ok(()) }
The text Time is written to file!, which is printed on the terminal.