Really strange behaviour of time crate

The below works:

"[day]-[month repr:short]-[year repr:last_two] [hour]:[minute]"

That one doesn't:

const DATE_FORMAT_STR: &'static str = "[day]-[month repr:short]-[year repr:last_two] [hour]:[minute]";

The error I'm getting:
error: expected string.

I've tried to convert it into String but no luck. I do see that the error is saying about some string type not String but still.
Is there anyway to make it work the second example is shown?

I believe this macros actually parses the format string at compile time (similar to format!).

Indeed. You have to use time::format_description::parse() if you want to pass a string value rather than a string literal. Unlike time::macros::format_description!() this will return a Result rather than give an error at compile time in case of an invalid format description.

Thanks, that helped!

If your goal is merely to avoid the need to copy-paste the string literal, and you don’t actually need to parse run-time-generated format strings, you can put the result of the format_description macro call in a const instead, avoiding the run-time overhead of using time::format_description::parse():

const FORMAT: &[time::format_description::FormatItem<'_>] = time::macros::format_description!(
    "[day]-[month repr:short]-[year repr:last_two] [hour]:[minute]"

Love it! Thanks!

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.