tailhook / humantime

A parser and formatter for std::time::{SystemTime, Duration}
Apache License 2.0
283 stars 34 forks source link

Format from duration to string #1

Closed lancecarlson closed 6 years ago

lancecarlson commented 6 years ago

Can you go from duration to a string? Seems like that would be super useful for view templates in web apps.

tailhook commented 6 years ago

It's not implemented. I want to implement it very much, but I'm not sure how to implement it so that it suits most users.

I mean there are a lot of options on length, rounding and other aspects of formatting.

Still it's a good idea to do. Do you know any good examples in other languages to compare?

lancecarlson commented 6 years ago

I suppose I would start off by implementing the same format that your parse_duration helper uses. From there, perhaps create constants for different kinds of formats you can serialize and deserialize. As for alternative formats, you can look at rails:

time_ago_in_words(3.minutes.from_now) # => 3 minutes time_ago_in_words(3.minutes.ago) # => 3 minutes time_ago_in_words(Time.now - 15.hours) # => about 15 hours time_ago_in_words(Time.now) # => less than a minute time_ago_in_words(Time.now, include_seconds: true) # => less than 5 seconds

from_time = Time.now - 3.days - 14.minutes - 25.seconds time_ago_in_words(from_time) # => 3 days

from_time = (3.days + 14.minutes + 25.seconds).ago time_ago_in_words(from_time) # => 3 days

tailhook commented 6 years ago

It must support round-tripping the date. But:

let start = Instant::now();
print!("{}", format_duration(start.elapsed()))

Will yield something unreadable like:

5 hours 3 mins 34 secs 102354323 nanos

This isn't something users want to see. We want something like this:

5h 3min

More questions:

  1. How zero is represented: 0 sec or 0 min or 0 nanos ?
  2. Short or long names h or hours, s or seconds ?
  3. 5400 sec is 90 min or 1 h 30 min ?
  4. Is 10 seconds a just now or 10 sec 345 millis ? Is 12 hours a tomorrow or 24 hours is ?
lancecarlson commented 6 years ago
  1. I think seconds are a sane default.
  2. This should be configurable but default to the long view
  3. I'd opt for the most divisible unit.. so 1h 30m
  4. 10s is a good default, but make it configurable. No milliseconds. Tomorrow, you have to calculate relative to today and the timezone. If you have that information, then it would be based on whatever midnight is.
lancecarlson commented 6 years ago

@tailhook Any additional thoughts to this spec?

tailhook commented 6 years ago

I'm sure some questions will pop up during the implementation. Probably, I will not have time to tackle this soon. Do you want to make a PR?

tailhook commented 6 years ago

Okay, just pushed v1.1.0-beta.2 with duration formatting. Note: that default format is not fixed, though. I.e. it's guaranteed to parse back to the same value, but details might be changed for clarity.