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>)
| 476 | /// // Output: "2 hours ago" |
| 477 | /// ``` |
| 478 | pub fn format_timestamp_relative(timestamp: &DateTime<Utc>) -> String { |
| 479 | let now = Utc::now(); |
| 480 | let duration = now.signed_duration_since(*timestamp); |
| 481 | |
| 482 | if duration.num_seconds() < 60 { |
| 483 | "just now".to_string() |
| 484 | } else if duration.num_minutes() < 60 { |
| 485 | let mins = duration.num_minutes(); |
| 486 | if mins == 1 { |
| 487 | "1 minute ago".to_string() |
| 488 | } else { |
| 489 | format!("{} minutes ago", mins) |
| 490 | } |
| 491 | } else if duration.num_hours() < 24 { |
| 492 | let hours = duration.num_hours(); |
| 493 | if hours == 1 { |
| 494 | "1 hour ago".to_string() |
| 495 | } else { |
| 496 | format!("{} hours ago", hours) |
| 497 | } |
| 498 | } else if duration.num_days() < 7 { |
| 499 | let days = duration.num_days(); |
| 500 | if days == 1 { |
| 501 | "yesterday".to_string() |
| 502 | } else { |
| 503 | format!("{} days ago", days) |
| 504 | } |
| 505 | } else if duration.num_weeks() < 4 { |
| 506 | let weeks = duration.num_weeks(); |
| 507 | if weeks == 1 { |
| 508 | "1 week ago".to_string() |
| 509 | } else { |
| 510 | format!("{} weeks ago", weeks) |
| 511 | } |
| 512 | } else { |
| 513 | // For older dates, use absolute format |
| 514 | format_timestamp(timestamp) |
| 515 | } |
| 516 | } |
| 517 | |
| 518 | /// Format a byte size in human-readable form. |
| 519 | /// |