Formatting Time Differences in Laravel 5
Displaying a timestamp as a raw date string often feels disconnected from the user's immediate context. When a visitor sees updated_at: 2015-06-22 20:00:03, they have to mentally calculate how much time has passed since then. A human-readable format like "25 mins ago" or "3 days ago" instantly conveys urgency and recency. In Laravel 5, achieving this requires moving beyond simple date formatting functions and understanding how to calculate the delta between two moments in time.
The core logic involves calculating the difference in seconds between the current moment (now) and the database timestamp stored in your updated_at column. Once you have that raw difference, you can apply a set of thresholds to determine whether the duration is best expressed in minutes, hours, or days. This approach allows you to keep the output concise while maintaining accuracy across different time scales.
You can start by using Laravel's built-in now() helper and the Eloquent model's updated_at accessor. Since updated_at is typically a Carbon instance (or compatible with it), you can leverage Carbon's powerful methods to perform arithmetic on dates without needing to manually convert them to timestamps.
use Carbon\Carbon;
$diff = now()->diffForHumans($post->updated_at);
// Output: "25 mins ago" or similar depending on the threshold logic applied below
While diffForHumans() is a convenient method, it defaults to showing weeks and years for larger durations. Your requirements specify that anything exceeding 59 minutes should be displayed in hours, and anything exceeding 24 hours should be displayed in days. To enforce this specific behavior, you might need to implement a custom logic or configure the diffForHumans options carefully.
Here is a practical implementation using Carbon's diffInRealMinutes, diffInHours, and daysSince methods to build a flexible formatter:
function getHumanReadableTime(Carbon $updatedAt, Carbon $now = null) {
if ($now === null) {
$now = now();
}
$seconds = $now->diffInSeconds($updatedAt);
// Less than 1 second? Usually treated as just now.
if ($seconds <= 0) {
return 'Just now';
}
// Check days first (24 hours threshold)
if ($seconds >= 86400) {
$days = $now->diffInDays($updatedAt, false);
return $days . ' day' . ($days > 1 ? 's' : '') . ' ago';
}
// Check hours (59 minutes threshold)
if ($seconds >= 3600) {
$hours = $now->diffInHours($updatedAt, false);
return $hours . ' hour' . ($hours > 1 ? 's' : '') . ' ago';
}
// Check minutes (59 seconds threshold)
if ($seconds >= 60) {
$minutes = $now->diffInMinutes($updatedAt, false);
return $minutes . ' min' . ($minutes > 1 ? 's' : '') . ' ago';
}
// Less than a minute
return 'Just now';
}
This function breaks the problem down into mutually exclusive ranges. By checking the largest unit first (days), then hours, and finally minutes, you ensure that a duration of 25 hours is reported as "1 day ago" rather than "41 hours ago", which aligns with standard human perception of time. The use of diffInHours(..., false) is critical here; the second argument ensures that partial hours are not rounded up, preserving precision for the specific thresholds you defined.
One potential pitfall in this implementation is handling timezone discrepancies. If your application runs on a server in one timezone but serves users in another, the calculation might appear incorrect to the end-user if the updated_at timestamp isn't stored in UTC or handled consistently. Always ensure that both the database column and the now() instance are aware of the same timezone context, preferably UTC for storage and conversion at display time.
If you prefer a more declarative approach without writing a custom function every time, you can extend Carbon with a global helper trait, though this adds complexity to your application's service layer. For most projects, keeping the logic isolated within a utility class or a dedicated model trait is cleaner and easier to maintain.
For further reading on Laravel helpers and date manipulation patterns, resources like https://laravelcompany.com offer deep dives into common architectural decisions that can simplify these types of repetitive tasks.