I wrote a silly Rust program inspired by a WolframAlpha query. I know, that's nothing serious, but if there's anything that could be made more, well, proper Rust-like, I'd love to know! Of course, general feedback is welcomed too.
For starters, here's my Cargo.toml
:
[package]
name = "rusted-days"
version = "0.1.0"
authors = ["baduker"]
edition = "2018"
[dependencies]
chrono = "0.4.19"
And the code:
use std::io;
use std::io::Write;
use chrono::{NaiveDateTime, DateTime, Utc, Datelike};
fn main() {
let prompt = "What's your date (DD/MM/YYYY)?: ";
let date = input(prompt).expect("Something went wrong! o.O");
show_interpretation(parse_date(date));
}
fn input(user_input: &str) -> io::Result<String> {
print!("{}", user_input);
io::stdout().flush()?;
let mut buffer: String = String::new();
io::stdin().read_line(&mut buffer)?;
Ok(buffer.trim_end().to_owned())
}
fn parse_date(date: String) -> DateTime<Utc> {
let naive_date = chrono::NaiveDate::parse_from_str(
date.as_str(), "%d/%m/%Y"
).unwrap();
let naive_datetime: NaiveDateTime = naive_date
.and_hms(0, 0, 0);
DateTime::<Utc>::from_utc(naive_datetime, Utc)
}
fn show_interpretation(date: DateTime<Utc>) {
println!("Input interpretation: days since {}", date.format("%A, %B %d, %Y"));
let total_days = Utc::now() - date;
println!("Result:\n{} days have rusted away ¯\\_(ツ)_/¯", total_days.num_days());
let years = Utc::now().year() - date.year();
let months = Utc::now().month() - date.month();
let days = Utc::now().day() - date.day();
println!("Timespan:\n{} year(s), {} month(s), {} day(s)", years, months, days);
println!("{} weeks", total_days.num_weeks());
println!("{:.2} years", total_days.num_days() as f32 / 365_f32);
}
A sample output (you should get):
What's your date (DD/MM/YYYY): 01/01/1970
Input interpretation: days since Thursday, January 01, 1970
Result:
18567 days have rusted away ¯\_(ツ)_/¯
Timespan:
50 years, 10 month(s), 0 days
2652 weeks
50.87 years