Laravel (Carbon) display date difference only in days
When working with timestamps stored in your database, you often need to present data in a specific way to your users. A common requirement is calculating the age of a record or the time elapsed since an event occurred. While diffForHumans() provides a convenient default output like "2 years ago" or "3 weeks ago," this behavior can be misleading when you only care about the day count. If an item was created three days and four hours ago, displaying it as "3 days ago" is accurate enough for your UI, but showing "3 days, 4 hours ago" might clutter the interface unnecessarily.
To achieve a display that strictly shows the difference in days, you need to manipulate the Carbon instance returned by diffForHumans(). The standard method returns a string representation of the interval, but it does not offer a built-in option to truncate the output to just days without including years or months if they exist.
Consider this scenario where you have a model property $price->created_at containing the string "2014-04-28". You might initially write code similar to this:
\Carbon\Carbon::createFromTimestamp(strtotime($price->created_at))->diffForHumans();
This approach relies on strtotime() to parse the string into a timestamp, then converts it back to a Carbon instance. While functional, this pattern is slightly fragile depending on the locale settings of the server or the format of the input string. It's generally safer and more idiomatic in Laravel to use the model attribute directly if it is already formatted as a date string, or cast it properly using CarbonImmutable for consistency across your application:
use Carbon\Carbon;
$carbonDate = Carbon::parse($price->created_at);
Once you have a valid Carbon instance representing the creation date, you can calculate the difference relative to "now." The diffForHumans() method is flexible and accepts an array of options. To suppress the inclusion of years, months, or hours, you must explicitly set these values to zero in the options array.
Here is how you configure the call to ensure only days are displayed:
$daysDiff = Carbon::parse($price->created_at)->diffForHumans([
'parts' => false, // This prevents "2 years ago" from appearing if > 2 years have passed
'options' => [
\Carbon\CarbonInterface::ABSOLUTE | \Carbon\CarbonInterface::SHORT,
\Carbon\CarbonInterface::DIFF_INCLUDES_DAYS_ONLY // Custom logic needed below
]
]);
Wait, that specific combination of flags isn't quite right for the "days only" constraint in a single pass. The diffForHumans() method actually has a simpler approach when you want to limit the granularity. You can pass a specific number of days as a negative integer to simulate looking forward from the date, but that's overcomplicating it.
The most direct way to force "days only" is to use the diff()->days property combined with logic to handle cases where the difference might be less than a day, or greater than 365 days. However, if you strictly want the human-readable string but without years or months, you can use the diffForHumans with specific formatting options that prioritize the smallest unit greater than zero, but filter out units larger than days.
Actually, there is a cleaner solution using CarbonPeriod or simply formatting the raw difference. But let's stick to modifying the output of diffForHumans(). If you check the documentation for diffForHumans, you'll see it returns a string like "3 years ago". To get just the days regardless of how many years have passed, you should calculate the total number of days between now and the created date.
use Carbon\Carbon;
$createdDate = Carbon::parse($price->created_at);
$now = Carbon::now();
// Calculate total days difference
$totalDays = $now->diffInDays($createdDate, false); // false means include future dates if applicable
// Handle formatting based on the result
if ($totalDays < 0) {
// Record is in the future
$display = "in {$totalDays} days";
} elseif ($totalDays == 0) {
$display = "today";
} elseif ($totalDays > 365) {
// If you strictly want days even for years, show the number
$display = "{$totalDays} days ago";
} else {
// For anything less than a year, just show days
$display = "{$totalDays} days ago";
}
This approach bypasses the diffForHumans() logic entirely. Why? Because diffForHumans() defaults to showing years if the span is greater than 365 days. If your business logic requires displaying "730 days" instead of "2 years", the raw calculation is more reliable. This ensures consistency across different time zones and avoids locale-specific formatting issues that might arise with diffForHumans().
If you prefer to stick with diffForHumans() but want to force the output to be day-centric, you can use the withMinDays option (available in newer Carbon versions) or simply accept that for long-term data, raw day counts are often clearer than "years". The trade-off here is between readability and precision. Displaying "2 years ago" is more human-friendly, but displaying "730 days ago" provides a precise metric useful for analytics or sorting logs without ambiguity about leap years or month lengths.
In summary, if your goal is to show the duration strictly in days, calculating diffInDays and formatting the string manually gives you full control over the output. This eliminates the risk of Carbon defaulting to "years" for large intervals, ensuring your UI always presents a uniform unit of measurement regardless of how much time has passed since the record was created.
