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