The simple use of Date and Time Processing Package Carbon in Laravel, laravelcarbon
Preface
We often need to process the date and time when writing PHP applications. This article will show you how to extend the Carbon-inherited API extensions from the PHP DateTime class, which makes processing date and time easier.
In Laravel, the default time processing class is Carbon.
<?php
namespace Carbon;
class Carbon extends \DateTime
{
// code here
}
You can see the code snippet declared above in the Carbon class of the Carbon namespace.
Install
You can use Composer to install Carbon:
composer require nesbot/carbon
PS:This package is installed by default in the Laravel project, so you do not need to execute the preceding command again.
Use
You need to use the namespace to import Carbon, instead of providing the complete name every time.
use Carbon\Carbon;
Get current time
You can use the now () method to obtain the current date and time. If you do not specify a parameter, it uses the time zone configured in PHP:
<?php
echo Carbon::now(); //2016-10-14 20:21:20
?>
If you want to use a different time zone, you need to pass a valid time zone as the parameter:
// Directly use the string echo Carbon: now ('Europe/London ');
// 20:21:20 // or echo Carbon :: now (new DateTimeZone ('Europe/London '));
Divisionnow()In additiontoday(),tomorrow(),yesterday()And other static functions, however, they are all at 00:00:00:
echo Carbon::now(); // 2016-10-14 15:18:34
echo Carbon::today(); // 2016-10-14 00:00:00
echo Carbon::tomorrow('Europe/London'); // 2016-10-14 00:00:00
echo Carbon::yesterday(); // 2016-10-14 00:00:00
The above output is actually a date and time object of the Carbon type:
Carbon {#179 ▼
+"date": "2016-06-14 00:00:00.000000"
+"timezone_type": 3
+"timezone": "UTC"
}
To obtain a date of the string type, use the following code:
echo Carbon::today()->toDateTimeString();
echo Carbon::yesterday()->toDateTimeString();
echo Carbon::tomorrow()->toDateTimeString();
Convert the date type to a string
As mentioned above, by default, the Carbon method returns a date and time object. Although it is an object, you can directly use echo to output the result because of the _ toString magic method. However, if you want to convert it into a string, you can use the toDateString or toDateTimeString method:
echo Carbon::now()->toDateString(); //2016-10-14echo Carbon::now()->toDateTimeString(); //2016-10-14 20:22:50
Date Parsing
You can also use the parse method to parse any order and type of date (the result is a date and time object of the Carbon type ):
echo Carbon::parse('2016-10-15')->toDateTimeString(); //2016-10-15 00:00:00
echo Carbon::parse('2016-10-15')->toDateTimeString(); //2016-10-15 00:00:00
echo Carbon::parse('2016-10-15 00:10:25')->toDateTimeString(); //2016-10-15 00:10:25
echo Carbon::parse('today')->toDateTimeString(); //2016-10-15 00:00:00
echo Carbon::parse('yesterday')->toDateTimeString(); //2016-10-14 00:00:00
echo Carbon::parse('tomorrow')->toDateTimeString(); //2016-10-16 00:00:00
echo Carbon::parse('2 days ago')->toDateTimeString(); //2016-10-13 20:49:53
echo Carbon::parse('+3 days')->toDateTimeString(); //2016-10-18 20:49:53
echo Carbon::parse('+2 weeks')->toDateTimeString(); //2016-10-29 20:49:53
echo Carbon::parse('+4 months')->toDateTimeString(); //2017-02-15 20:49:53
echo Carbon::parse('-1 year')->toDateTimeString(); //2015-10-15 20:49:53
echo Carbon::parse('next wednesday')->toDateTimeString(); //2016-10-19 00:00:00
echo Carbon::parse('last friday')->toDateTimeString(); //2016-10-14 00:00:00
Construction Date
You can also use a separate year, month, and day to construct a date:
$year = '2015';
$month = '04';
$day ='12';
echo Carbon::createFromDate($year, $month, $day); //2015-04-12 20:55:59
$hour = '02';
$minute = '15':
$second = '30';
echo Carbon::create($year, $month, $day, $hour, $minute, $second); //2015-04-12 02:15:30
Echo carbon:: createfromdate (null, 12, 25); / / year defaults to current year
In addition, a valid time zone can be passed as the last parameter.
Date operation
The date operation can be completed by adding (add) or sub (minus) to keep up with the units to be added or subtracted. For example, if you want to add a specified number of days to a date, you can use the addDays method. In addition, a modify method is provided. The parameter format is + or-followed by the value and unit. Therefore, if you want to add a year to the current date, you can pass + 1 year:
echo Carbon::now()->addDays(25); //2016-11-09 14:00:01
echo Carbon::now()->addWeeks(3); //2016-11-05 14:00:01
echo Carbon::now()->addHours(25); //2016-10-16 15:00:01
echo Carbon::now()->subHours(2); //2016-10-15 12:00:01
echo Carbon::now()->addHours(2)->addMinutes(12); //2016-10-15 16:12:01
echo Carbon::now()->modify('+15 days'); //2016-10-30 14:00:01
echo Carbon::now()->modify('-2 days'); //2016-10-13 14:00:01
Date comparison
In Carbon, you can use the following method to compare dates:
- Min-returns the minimum date.
- Max-returns the maximum date.
- Eq-determine whether two dates are equal.
- Gt-determine whether the first date is greater than the second date.
- Lt-determine whether the first date is smaller than the second date.
- Gte-determine whether the first date is greater than or equal to the second date.
- Lte-determine whether the first date is less than or equal to the second date.
echo Carbon::now()->tzName; // America/Toronto
$first = Carbon::create(2012, 9, 5, 23, 26, 11);
$second = Carbon::create(2012, 9, 5, 20, 26, 11, 'America/Vancouver');
echo $first->toDateTimeString(); // 2012-09-05 23:26:11
echo $first->tzName; // America/Toronto
echo $second->toDateTimeString(); // 2012-09-05 20:26:11
echo $second->tzName; // America/Vancouver
var_dump($first->eq($second)); // bool(true)
var_dump($first->ne($second)); // bool(false)
var_dump($first->gt($second)); // bool(false)
var_dump($first->gte($second)); // bool(true)
var_dump($first->lt($second)); // bool(false)
var_dump($first->lte($second)); // bool(true)
$first->setDateTime(2012, 1, 1, 0, 0, 0);
$second->setDateTime(2012, 1, 1, 0, 0, 0); // Remember tz is 'America/Vancouver'
var_dump($first->eq($second)); // bool(false)
var_dump($first->ne($second)); // bool(true)
var_dump($first->gt($second)); // bool(false)
var_dump($first->gte($second)); // bool(false)
var_dump($first->lt($second)); // bool(true)
var_dump($first->lte($second)); // bool(true)
To determine whether a date is between two dates, you can use the between () method. The third optional parameter specifies whether the comparison can be equal. The default value is true:
$first = Carbon::create(2012, 9, 5, 1);
$second = Carbon::create(2012, 9, 5, 5);
var_dump(Carbon::create(2012, 9, 5, 3)->between($first, $second)); // bool(true)
var_dump(Carbon::create(2012, 9, 5, 5)->between($first, $second)); // bool(true)
var_dump(Carbon::create(2012, 9, 5, 5)->between($first, $second, false)); // bool(false)
In addition, you can also provide some auxiliary methods to clarify their meanings from their names:
$dt = Carbon::now();
$dt->isWeekday();
$dt->isWeekend();
$dt->isYesterday();
$dt->isToday();
$dt->isTomorrow();
$dt->isFuture();
$dt->isPast();
$dt->isLeapYear();
$dt->isSameDay(Carbon::now());
$born = Carbon::createFromDate(1987, 4, 23);
$noCake = Carbon::createFromDate(2014, 9, 26);
$yesCake = Carbon::createFromDate(2014, 4, 23);
$overTheHill = Carbon::now()->subYears(50);
var_dump($born->isBirthday($noCake)); // bool(false)
var_dump($born->isBirthday($yesCake)); // bool(true)
var_dump($overTheHill->isBirthday()); // bool(true) -> default compare it to today!
DiffForHumans
"One month ago" is easier to read than "30 days ago". Many date libraries provide this common feature. After a date is parsed, there are four possibilities:
1. When the comparison time exceeds the current default time
- 1 day ago
- Before January 1, May
2. Compare future time with the current default time
3. When the Compare value exceeds another value
- 1 hour ago
- Before January 1, May
4. When the Compare value is after another value
- 1 hour later
- After January 1, May
You can set the second parameter to true to delete modifiers such as "front" and "current:diffForHumans(Carbon $other, true).
Echo carbon:: now() - > subdays (5) - > diffforhumans(); / / 5 days ago
Echo carbon:: now() - > diffforhumans (carbon:: now() - > subyear()); / / 1 year later
$dt = Carbon::createFromDate(2011, 8, 1);
Echo $DT - > diffforhumans ($DT - > copy() - > addmonth()); / / 1 month ago
Echo $DT - > diffforhumans ($DT - > copy() - > submonth()); / / after November
Echo carbon:: now() - > addseconds (5) - > diffforhumans(); / / 5 seconds from now
Echo carbon:: now() - > subdays (24) - > diffforhumans(); / / 3 weeks ago
Echo carbon:: now() - > subdays (24) - > diffforhumans (null, true); / / 3 weeks
Localization
In app/Providers/AppServiceProvider. phpboot()Add the following code to set global localization:
public function boot(){ \Carbon\Carbon::setLocale('zh');}
After setting, call at the output time:
$article->created_at->diffForHumans();
Similar format.
For more Carbon operations, see the documentation.
Summary
The above is all the content of this article. I hope the content of this article will help you in your study or work. If you have any questions, please leave a message, thank you for your support.