time icon indicating copy to clipboard operation
time copied to clipboard

Permit skipping `[optional]` values when formatting

Open MaxKingPor opened this issue 1 year ago • 5 comments

How to format optional as empty

MaxKingPor avatar Sep 25 '24 03:09 MaxKingPor

Can you share some code? I'm not certain what you're referring to.

jhpratt avatar Sep 25 '24 05:09 jhpratt

Can you share some code? I'm not certain what you're referring to.

    #[test]
    fn test_format() {
        let format =
            time::macros::format_description!(version = 2, "[year]-[month]-[optional [[day]]]");

        // let mut format = format_description!(version = 2, "[year]-[month]-[optional format:false [[day]]]");
        // format.format_optional(false)
        
        let date = time::Date::from_calendar_date(2024, time::Month::April, 1).unwrap();

        let str = date.format(format).unwrap(); // --> format to "2024-04-"
                                                // assert_eq!(str,"2024-04-");
        println!("{:?}", str)
    }

MaxKingPor avatar Sep 25 '24 06:09 MaxKingPor

Why is this needed? Generally you should be providing as much information as possible when formatting, only inferring when parsing if absolutely necessary. The description in documentation matches this:

An item that may or may not be present while parsing. While formatting, the value is always present.

jhpratt avatar Sep 25 '24 06:09 jhpratt

Why is this needed? Generally you should be providing as much information as possible when formatting, only inferring when parsing if absolutely necessary. The description in documentation matches this:

An item that may or may not be present while parsing. While formatting, the value is always present.

Format it into a simpler form when supporting more formats

pub const FORMAT: &[time::format_description::BorrowedFormatItem] = time::macros::format_description!(
    version = 2,
    "[year]-[month]-[day][first [ ] [T]][hour]:[minute]:[second][optional [[first [[end]] [.[subsecond digits:1+]]]]][optional [[first [[end]] [[offset_hour]:[offset_minute][optional [:[offset_second]]]]]]]"
);


Just like this, if I want to format the time zone without formatting milliseconds, I can't do it

MaxKingPor avatar Sep 25 '24 06:09 MaxKingPor

Unfortunately the optional component does not permit modifiers in the current public API and said API is not marked #[non_exhaustive]. As such, it would be a breaking change to implement this. I'll add it to the list in #650.

jhpratt avatar Oct 21 '24 07:10 jhpratt