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