From 1bba2f798f27e20f5b8f7053bdfab02ae5b2fff8 Mon Sep 17 00:00:00 2001 From: ducdetronquito Date: Sat, 23 Dec 2023 15:25:31 +0100 Subject: [PATCH] feat: Display the person's age --- src/lib.rs | 11 ++++++++--- src/main.rs | 13 +++++++++++-- 2 files changed, 19 insertions(+), 5 deletions(-) diff --git a/src/lib.rs b/src/lib.rs index 6ee358d..193fcda 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -25,10 +25,15 @@ pub fn add_birthday(name: String, date: String) -> Result<()> { Ok(()) } -#[derive(Debug)] pub struct Birthday { - name: String, - date: NaiveDate, + pub name: String, + pub date: NaiveDate, +} + +impl Birthday { + pub fn age(&self, today: NaiveDate) -> Option { + today.years_since(self.date) + } } pub fn get_all_birthdays() -> Result> { diff --git a/src/main.rs b/src/main.rs index c034bf9..1916214 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,5 +1,6 @@ use anyhow::Result; -use birthday::{add_birthday, Birthday}; +use birthday::Birthday; +use chrono::Utc; use clap::{Parser, Subcommand}; #[derive(Parser, Debug)] @@ -32,8 +33,16 @@ enum Command { } fn print_birthdays(birthdays: Vec) { + let today = Utc::now().date_naive(); for birthday in birthdays { - println!("{:?}", birthday); + let age = match birthday.age(today) { + Some(age) => age.to_string(), + None => "".to_owned(), + }; + println!( + "Name={} Birthdate={} Age={}", + birthday.name, birthday.date, age + ); } }