Home »
Rust »
Rust Programs
Rust program to parse the date and time from a string
Rust | Date & Time Example: Write a program to parse the date and time from a string.
Submitted by Nidhi, on November 10, 2021
Problem Solution:
In this program, we will parse date and time from string using the parse_from_str() function and print the result.
Add Chrono date-time external library to your project
-
Create your project using the below command.
$cargo new datetime -bin
-
Goto the project folder cd datetime and edit Cargo.toml file.
$datetime>nano Cargo.toml
-
Then add dependency in Cargo.toml file
[dependencies]
chrono = "0.4"
-
After that, build your project using the below command
$datetime>cargo build
-
Then execute your project after modification in src/main.rs source file.
$datetime>cargo run
Program/Source Code:
The source code to parse the date and time from the string is given below. The given program is compiled and executed on UBUNTU 18.04 successfully.
// Rust program to parse date and time
// from the string
use chrono::{DateTime, NaiveDate, NaiveDateTime, NaiveTime};
use chrono::format::ParseError;
fn main() -> Result<(), ParseError> {
let date_time = NaiveDateTime::parse_from_str("2021-10-29 13:46:24", "%Y-%m-%d %H:%M:%S")?;
println!("Parsed date and time is: {}", date_time);
Ok(())
}
Output:
$datetime> cargo run
Compiling datetime v0.1.0 (/home/arvind/Desktop/rust/datetime)
Finished dev [unoptimized + debuginfo] target(s) in 0.27s
Running `target/debug/datetime`
Parsed date and time is: 2021-10-29 13:46:24
Explanation:
In the above program, we imported the "Chrono" library to our project for performing date and time operations. We imported the Chrono library using the below line:
use chrono::Utc;
In the main() function, we called NaiveTime::parse_from_str() function to parse the string into date-time and print the result.
Rust Date and Time Programs »