/*
Use integer division and modulo:
1 minute = 60 seconds
1 hour = 60 minutes
1 day = 24 hours
1 week = 7 days
*/
/*
Convert a total number of seconds into weeks, days, hours,
minutes, and seconds. The function receives the total seconds
and returns each component in a struct.
*/
struct TimeParts {
weeks: i64,
days: i64,
hours: i64,
minutes: i64,
seconds: i64,
}
fn convert_seconds(mut total_seconds: i64) -> TimeParts {
const SECS_PER_MIN: i64 = 60;
const SECS_PER_HOUR: i64 = 60 * SECS_PER_MIN;
const SECS_PER_DAY: i64 = 24 * SECS_PER_HOUR;
const SECS_PER_WEEK: i64 = 7 * SECS_PER_DAY;
// Compute each unit using integer division and modulo
let weeks = total_seconds / SECS_PER_WEEK;
total_seconds %= SECS_PER_WEEK;
let days = total_seconds / SECS_PER_DAY;
total_seconds %= SECS_PER_DAY;
let hours = total_seconds / SECS_PER_HOUR;
total_seconds %= SECS_PER_HOUR;
let minutes = total_seconds / SECS_PER_MIN;
let seconds = total_seconds % SECS_PER_MIN;
TimeParts {
weeks,
days,
hours,
minutes,
seconds,
}
}
fn main() {
let seconds: i64 = 1_000_000;
let result = convert_seconds(seconds);
println!(
"{} weeks, {} days, {} hours, {} minutes, {} seconds",
result.weeks, result.days, result.hours, result.minutes, result.seconds
);
}
/*
run:
1 weeks, 4 days, 13 hours, 46 minutes, 40 seconds
*/