In this tutorial, we will learn date time format in Laravel.
You can see the following examples lists:
1) Format a Date
2) Format a Time
3) Format a Date and Time
- Custom Format
- Relative Formate
- Localization
- Timezones
- Date Intervals
- Date Comparison
- Carbon Macros
- Date Casting in Eloquent
- Displaying Dates in View
- Carbon Immutable
- Carbon Periods
Date Time Format in Laravel
The built-in PHP DateTime class can be used in Laravel to work with dates and timings. Laravel provides a set of helpful methods to work with dates and times in a convenient way.
The following are examples of how to format dates and times in Laravel:
1) Format a date
$date = new DateTime('2023-04-13');
$formattedDate = $date->format('Y-m-d'); // 2023-04-13
2) Format a time
$time = new DateTime('13:30:00');
$formattedTime = $time->format('H:i:s'); // 13:30:00
3) Format a date and time
$dateTime = new DateTime('2023-04-13 13:30:00');
$formattedDateTime = $dateTime->format('Y-m-d H:i:s'); // 2023-04-13 13:30:00
In Laravel, you can also use the Carbon
class to work with dates and times. Carbon
is a powerful extension to the PHP DateTime class that makes working with dates and times more convenient.
Here's an example of how to format a date using Carbon:
use Carbon\Carbon;
$date = Carbon::parse('2023-04-13');
$formattedDate = $date->format('Y-m-d'); // 2023-04-13
The parse()
method is used to create a new Carbon instance from a date string. You can then use the format()
method to format the date in the desired format.
The official documentation for Laravel can be found at https://laravel.com/ and provides more information on using dates and times.
Examples of how to work with date and time formats in Laravel:
a) Custom format
You can define a custom format using the DateTime::createFromFormat
method. Here's an example:
$dateString = '13-04-2023';
$date = DateTime::createFromFormat('d-m-Y', $dateString);
$formattedDate = $date->format('Y-m-d'); // 2023-04-13
In this above example, a string with the characters "d-m-Y
" is being converted into a DateTime object. We then format the date in the "Y-m-d" format.
b) Relative format
Carbon provides a convenient way to format dates and times in a relative format, such as "2 days ago" or "in 1 hour". Here's an example:
use Carbon\Carbon;
$date = Carbon::parse('2023-04-11');
$formattedDate = $date->diffForHumans(); // 2 days ago
In this example, we're using the diffForHumans()
method to format the date in a relative format.
c) Localization
Laravel also provides localization support for date and time formats. The config/app.php file allows you to specify the default language for date and time formats.
Example:
'locale' => 'en',
We are making English the default language in the aforementioned case. Using the setLocale() method, you may even change the language to one from a particular region:
use Carbon\Carbon;
Carbon::setLocale('es');
$date = Carbon::parse('2023-04-13');
$formattedDate = $date->formatLocalized('%A %d %B %Y'); // jueves 13 abril 2023
Using the setLocale() method, we're changing the language in this example to Spanish. The date is then formatted using the %A %d %B %Y
format, which produces the weekday, monthday, year, and month in the chosen language.
d) Timezones
Laravel also provides timezone support for working with dates and times in different time zones. You can set the default timezone in the config/app.php
file:
'timezone' => 'UTC',
In this example, we're setting the default timezone to UTC. You can also set the timezone on a per-request basis using the timezone()
method:
use Carbon\Carbon;
$date = Carbon::parse('2023-04-13');
$formattedDate = $date->timezone('America/New_York')->format('Y-m-d H:i:s'); // 2023-04-13 00:00:00
In this example, we're setting the timezone to "America/New_York" using the timezone()
method. We then format the date in the desired format.
e) Date intervals
Carbon also provides a convenient way to work with date intervals. You can use the add()
and sub()
methods to add or subtract a specified interval from a date. Here's an example:
use Carbon\CarbonInterval;
$date = Carbon::parse('2023-04-13');
$date->add(CarbonInterval::days(7));
$formattedDate = $date->format('Y-m-d'); // 2023-04-20
In this example, we're adding 7 days to the date using the add()
method and the CarbonInterval::days()
method.
f) Date comparison
You can compare two dates using the diff()
method, which returns a DateInterval
object representing the difference between the two dates. Here's an example:
use Carbon\Carbon;
$date1 = Carbon::parse('2023-04-13');
$date2 = Carbon::parse('2023-04-20');
$diff = $date1->diff($date2);
$daysDifference = $diff->days; // 7
In this example, we're comparing two dates and calculating the difference in days using the diff()
method and the days
property of the resulting DateInterval
object.
g) Carbon Macros
One of the most powerful features of Carbon in Laravel is the ability to create custom macros. Macros are essentially custom methods that you can define on the Carbon
class to extend its functionality.
Here's an example of how to create a custom macro:
use Carbon\Carbon;
Carbon::macro('weekdayName', function() {
$weekdays = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
return $weekdays[$this->dayOfWeek];
});
$date = Carbon::parse('2023-04-13');
$weekdayName = $date->weekdayName(); // Thursday
This example shows how to create a custom macro called weekdayName
that outputs the name of the weekday associated with the provided date. We're using the $this
keyword to refer to the Carbon
instance that the macro is called on.
h) Date casting in Eloquent
In Laravel's Eloquent ORM, you can specify how dates should be cast when retrieved from the database and when saved to the database. You can do this by adding a protected $casts
property to your Eloquent model:
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
protected $casts = [
'published_at' => 'datetime:Y-m-d',
];
}
In this example, we're casting the published_at
attribute to a datetime
format with the Y-m-d
format specifier. Meaning of this is that when the attribute is retrieved from the database, it will be automatically converted to a Carbon
instance with the specified format.
i) Displaying dates in views
In your Laravel views, you can use the {{ $date->format('Y-m-d') }}
syntax to display a formatted date. Alternatively, you can use the @datetime($date)
Blade directive to display a localized date with the user's preferred date format.
<div>
Date: {{ $date->format('Y-m-d') }}
</div>
<div>
Date: @datetime($date)
</div>
In this example, we're displaying the date twice: once with the format()
method, and once with the @datetime
Blade directive.
j) Localization
Laravel provides built-in support for localizing dates and times. You can use the setLocale()
method to set the locale for Carbon:
use Carbon\Carbon;
Carbon::setLocale('fr');
$date = Carbon::parse('2023-04-13');
$formattedDate = $date->formatLocalized('%A %d %B %Y'); // 13 April 2023
Using setLocale()
method, we can change locale to French. Then format the date using the formatLocalized()
method with a custom format string.
You can also use the @lang()
Blade directive to localize dates in your views:
<div>
Date: @lang('dates.date_format', ['date' => $date])
</div>
In this above example, we're using the @lang()
Blade directive to localize the date format. The date_format
key should be defined in your language files.
k) Carbon Immutable
By default, Carbon is a mutable class, meaning that modifying a Carbon
instance will modify the instance itself. On the other hand, you may use the CarbonImmutable
class to build a new Carbon instance out of an existing one:
use Carbon\CarbonImmutable;
$date = CarbonImmutable::parse('2023-04-13');
$nextWeek = $date->addWeek();
In this illustration, a new Carbon instance is created based on the old instance using the CarbonImmutable class. We then add a week to the new instance without modifying the original instance.
l) Carbon Periods
Carbon also provides a Period
class for working with date ranges. You can use the CarbonPeriod
class to iterate over a range of dates:
use Carbon\Carbon;
use Carbon\CarbonPeriod;
$startDate = Carbon::parse('2023-04-13');
$endDate = Carbon::parse('2023-04-20');
$period = CarbonPeriod::create($startDate, $endDate);
foreach ($period as $date) {
echo $date->format('Y-m-d');
}
In this above example, we're creating a CarbonPeriod
instance for the date range between $startDate
and $endDate
. We then iterate over the range and format each date.
These are just a few additional examples of how Laravel may be used to interact with dates and timings. The documentation for Laravel contains various other examples and explanations of how to use dates and times: https://laravel.com/