How do I make the friendly
format show units bigger than days?
#250
-
How to ask use jiff::{
civil::Date,
fmt::friendly::{Designator, SpanPrinter},
Zoned,
};
fn main() -> anyhow::Result<()> {
let date: Date = "2015-06-10".parse()?;
let span: jiff::Span = Zoned::now().date() - date;
println!("It has been {}", format!("{span:#}"));
println!("It has been {}", humanize(span));
Ok(())
}
// Turn duration into human readable format
fn humanize(span: jiff::Span) -> String {
dbg!(span);
let printer = SpanPrinter::new().designator(Designator::HumanTime);
printer.span_to_string(&span)
} 🦄 cargo r`
It has been 3534d
[src/main.rs:19:5] span = 3534d
It has been 3534d [dependencies]
jiff = "0.2"
anyhow = "1.0" |
Beta Was this translation helpful? Give feedback.
Answered by
BurntSushi
Feb 11, 2025
Replies: 1 comment 2 replies
-
Does the section on rounding help answer your question? For your code, I would do it like this, by specifying the largest unit: use jiff::{
civil::Date,
fmt::friendly::{Designator, SpanPrinter},
Unit, Zoned,
};
fn main() -> anyhow::Result<()> {
let date: Date = "2015-06-10".parse()?;
let span = Zoned::now().date().since((Unit::Year, date))?;
println!("It has been {}", format!("{span:#}"));
println!("It has been {}", humanize(span));
Ok(())
}
// Turn duration into human readable format
fn humanize(span: jiff::Span) -> String {
let printer = SpanPrinter::new().designator(Designator::HumanTime);
printer.span_to_string(&span)
} Has this output:
And note that you can do this directly on use jiff::{civil::Date, tz::TimeZone, Unit, Zoned};
fn main() -> anyhow::Result<()> {
let date: Date = "2015-06-10".parse()?;
let zdt = date.to_zoned(TimeZone::system())?;
let span = Zoned::now().date().since((Unit::Year, &zdt))?;
println!("It has been {}", format!("{span:#}"));
Ok(())
} Has this output:
And if you do subtraction between two zoned datetime and get "too many" units like this: use jiff::{tz::TimeZone, Unit, Zoned};
fn main() -> anyhow::Result<()> {
let zdt = "2015-06-10T17:30[Poland]"
.parse::<Zoned>()?
.with_time_zone(TimeZone::system());
let span = Zoned::now().since((Unit::Year, &zdt))?;
println!("It has been {}", format!("{span:#}"));
Ok(())
}
You can also specify the smallest unit, and Jiff will do automatic rounding for you: use jiff::{tz::TimeZone, Unit, Zoned, ZonedDifference};
fn main() -> anyhow::Result<()> {
let zdt = "2015-06-10T17:30[Poland]"
.parse::<Zoned>()?
.with_time_zone(TimeZone::system());
let span = Zoned::now().since(
ZonedDifference::new(&zdt).smallest(Unit::Second).largest(Unit::Year),
)?;
println!("It has been {}", format!("{span:#}"));
Ok(())
} Which gives:
|
Beta Was this translation helpful? Give feedback.
2 replies
Answer selected by
BurntSushi
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Does the section on rounding help answer your question?
For your code, I would do it like this, by specifying the largest unit:
Has this output: