Calculating the Difference Between Two Time Periods in Rust
Rust is a modern systems programming language that emphasizes safety and performance. While working with date and time operations, Rust offers excellent support through the chrono
crate.
This crate enables developers to manipulate and format date-time values easily, including calculating the duration between two moments in time.
In this sub-article, we’ll implement a simple Rust program to calculate the time difference between two points using NaiveDateTime
objects. This example follows the idea from our C lead article, reimagined in idiomatic Rust.
Required Crate
Add the following to your Cargo.toml
dependencies:
chrono = "0.4"
You must include the chrono
crate for date-time operations in Rust.
Rust Program: Calculate the Difference Between Two Time Periods
// DIFFERENCE BETWEEN TWO TIME PERIODS in Rust using chrono crate
use chrono::{NaiveDateTime, Duration};
fn main() {
// Step-1 Define the start and end time using NaiveDateTime
let start_time = NaiveDateTime::parse_from_str("2025-08-10 07:45:30", "%Y-%m-%d %H:%M:%S").unwrap();
let end_time = NaiveDateTime::parse_from_str("2025-08-18 16:25:15", "%Y-%m-%d %H:%M:%S").unwrap();
// Step-2 Calculate the duration between the two times
let duration = end_time - start_time;
// Step-3 Extract total seconds, then compute hours, minutes, and seconds
let total_seconds = duration.num_seconds();
let hours = total_seconds / 3600;
let minutes = (total_seconds % 3600) / 60;
let seconds = total_seconds % 60;
// Step-4 Display the result
println!("\nTIME DIFFERENCE: {} HOURS, {} MINUTES, {} SECONDS", hours, minutes, seconds);
}
Output
TIME DIFFERENCE: 208 HOURS, 39 MINUTES, 45 SECONDS
Explanation
-
NaiveDateTime
is used here as we don’t require timezone awareness. -
The
parse_from_str()
method lets us easily define specific date-time values. -
The subtraction of two
NaiveDateTime
instances returns aDuration
, which gives access to second-based intervals.
This pattern is ideal for CLI tools, backend services, or any application in Rust that requires precise time computations.
Extra Metric: Total Duration in Minutes
You can also calculate the total duration in minutes:
let total_minutes = duration.num_minutes();
println!("TOTAL DURATION IN MINUTES: {}", total_minutes);
Output
TOTAL DURATION IN MINUTES: 12519
This is helpful for analytics, summaries, or any cumulative tracking system.