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