rtlibs-utils 0.1.6

rtools library: utilities
Documentation
// FORMAT DD/MM/YYYY

use time::Date;
use time::Month;

pub fn to_dmy(
    date: Date
) -> (
    u8,
    u8,
    u16,
)
{
    let day = date.day();
    let month = date.month() as u8;
    let year: u16 = date
        .year()
        .try_into()
        .unwrap_or(1900);
    (
        day, month, year,
    )
}

pub fn to_string<S>(
    date: Date,
    sep: S,
    display: bool,
) -> String
where
    S: AsRef<str>,
{
    let inner = move |sep: &str| {
        let date_day = date.day();
        let date_month = date.month() as u8;
        let date_year = date.year();
        if display
        {
            format!("{date_day:02}{sep}{date_month:02}{sep}{date_year:04}")
        }
        else
        {
            format!("{date_year:04}{sep}{date_month:02}{sep}{date_day:02}")
        }
    };

    inner(sep.as_ref())
}

pub fn parse<S>(s: S) -> Option<Date>
where
    S: AsRef<str>,
{
    let inner = move |s: &str| {
        let day: u8 = (s[0..2])
            .parse()
            .unwrap_or(1);
        let month_index: u8 = (s[3..5])
            .parse::<u8>()
            .map(|i| i.saturating_sub(1))
            .unwrap_or(0);
        let month = Month::January.nth_next(month_index);
        let year: i32 = (s[6..10])
            .parse()
            .unwrap_or(1900);
        Date::from_calendar_date(
            year, month, day,
        )
        .ok()
    };

    inner(s.as_ref())
}