Format a timestamp in a relative format (e.g., "2 hours ago"). This provides a more conversational representation of time that's easier to understand at a glance. # Arguments `timestamp` - The UTC timestamp to format # Returns A relative time string. # Example ```rust,ignore let ts = Utc::now() - chrono::Duration::hours(2); println!("{}", format_timestamp_relative(&ts)); // Output: "2 hours
(timestamp: &DateTime<Utc>)
| 598 | /// // Output: "2 hours ago" |
| 599 | /// ``` |
| 600 | pub fn format_timestamp_relative(timestamp: &DateTime<Utc>) -> String { |
| 601 | let now = Utc::now(); |
| 602 | let duration = now.signed_duration_since(*timestamp); |
| 603 | |
| 604 | if duration.num_seconds() < 60 { |
| 605 | "just now".to_string() |
| 606 | } else if duration.num_minutes() < 60 { |
| 607 | let mins = duration.num_minutes(); |
| 608 | if mins == 1 { |
| 609 | "1 minute ago".to_string() |
| 610 | } else { |
| 611 | format!("{} minutes ago", mins) |
| 612 | } |
| 613 | } else if duration.num_hours() < 24 { |
| 614 | let hours = duration.num_hours(); |
| 615 | if hours == 1 { |
| 616 | "1 hour ago".to_string() |
| 617 | } else { |
| 618 | format!("{} hours ago", hours) |
| 619 | } |
| 620 | } else if duration.num_days() < 7 { |
| 621 | let days = duration.num_days(); |
| 622 | if days == 1 { |
| 623 | "yesterday".to_string() |
| 624 | } else { |
| 625 | format!("{} days ago", days) |
| 626 | } |
| 627 | } else if duration.num_weeks() < 4 { |
| 628 | let weeks = duration.num_weeks(); |
| 629 | if weeks == 1 { |
| 630 | "1 week ago".to_string() |
| 631 | } else { |
| 632 | format!("{} weeks ago", weeks) |
| 633 | } |
| 634 | } else { |
| 635 | // For older dates, use absolute format |
| 636 | format_timestamp(timestamp) |
| 637 | } |
| 638 | } |
| 639 | |
| 640 | /// Format a byte size in human-readable form. |
| 641 | /// |