This article mainly introduces you to the relevant knowledge about PHP. Carbon is PHP’s date processing library (A simple PHP API extension for DateTime.), which inherits PHP’s Datetime class. Below Let me explain the use of this class, I hope it will be helpful to everyone.
(Recommended tutorial: PHP video tutorial)
Carbon is date processing in php Class library (A simple PHP API extension for DateTime.).
Carbon inherits PHP’s Datetime class, so the methods that are not involved in Carbon but have been implemented in Datetime can be used.
Look at the code
<?php namespace Carbon; class Carbon extends \DateTime { // code here }
The Carbon class is declared under the Carbon namespace. You can introduce the namespace instead of entering the complete class name each time.
<?php use Carbon\Carbon;
Note: If you do not specifically set the time zone when using Carbon, the America/Toronto time zone will be used by default.
Pay special attention to whether the correct time zone is used. For example, all differences in Carbon use UTC or the time zone set by the system.
<?php $dtToronto = Carbon::createFromDate(2012, 1, 1, 'America/Toronto'); $dtVancouver = Carbon::createFromDate(2012, 1, 1, 'America/Vancouver'); echo $dtVancouver->diffInHours($dtToronto); // 3
The time comparison performed above is done in the time zone of the provided Carbon instance. For example, the author's time zone is Tokyo time minus 13 hours, so it is after 1 p.m. Carbon::now(‘Asia/Tokyo’)->isToday() will return false. If the time zone is set to Tokyo time zone when calling now(), it is unreasonable to use Tokyo time zone for subsequent operations. So when comparing to an instance created by now() the default is done in the current time zone.
There are several ways to create an instance of Carbon, but everyone should prefer to implement it through this semantic static method.
<?php $carbon = new Carbon(); // equivalent to Carbon::now() $carbon = new Carbon('first day of January 2008', 'America/Vancouver'); echo get_class($carbon); // 'Carbon\Carbon' $carbon = Carbon::now(-5);
It is worth noting that the second parameter of the Carbon constructor has been enhanced to not only be limited to \DateTimeZone instances, but also can be String or Integer (indicating the offset value relative to GMT). Let’s take an example to illustrate the now() method.
<?php $now = Carbon::now(); $nowInLondonTz = Carbon::now(new DateTimeZone('Europe/London')); // or just pass the timezone as a string $nowInLondonTz = Carbon::now('Europe/London'); // or to create a date with a timezone of +1 to GMT during DST then just pass an integer echo Carbon::now(1)->tzName; // Europe/London
You will like using the parse() method to replace the original cumbersome construction method
<?php echo (new Carbon('first day of December 2008'))->addWeeks(2); // 2008-12-15 00:00:00 echo Carbon::parse('first day of December 2008')->addWeeks(2); // 2008-12-15 00:00:00
Methods similar to now() that directly return Carbon instances include today(), tomorrow (), yesterday(), they all accept a timezone type parameter, and the time part of the final result is 00:00:00
<?php $now = Carbon::now(); echo $now; // 2016-06-24 15:18:34 $today = Carbon::today(); echo $today; // 2016-06-24 00:00:00 $tomorrow = Carbon::tomorrow('Europe/London'); echo $tomorrow; // 2016-06-25 00:00:00 $yesterday = Carbon::yesterday(); echo $yesterday; // 2016-06-23 00:00:00
The following are some other static methods in the form of creatXXX(). The parameters of most static methods can be passed or not. If they are not passed, the default values preset by the method will be used. These preset values are generally based on the current date, time, and time zone. If a required parameter is not passed, an exception of type InvalidArgumentException will be thrown. Use the DateTime::getLastErrors() method to get the details of the exception.
<?php Carbon::createFromDate($year, $month, $day, $tz); Carbon::createFromTime($hour, $minute, $second, $tz); Carbon::create($year, $month, $day, $hour, $minute, $second, $tz);
createFromDate() returns the current time by default, and the createFromTime() date defaults to today. All null parameters of crete() will default to the current corresponding time. Likewise, the time zone defaults to the current time zone. If only the hours are set but not the minutes and seconds, the minutes and seconds default to 0
<?php $xmasThisYear = Carbon::createFromDate(null, 12, 25); // Year defaults to current year $Y2K = Carbon::create(2000, 1, 1, 0, 0, 0); $alsoY2K = Carbon::create(1999, 12, 31, 24); $noonLondonTz = Carbon::createFromTime(12, 0, 0, 'Europe/London'); // A two digit minute could not be found try { Carbon::create(1975, 5, 21, 22, -2, 0); } catch(InvalidArgumentException $x) { echo $x->getMessage(); }
<?php Carbon::createFromFormat($format, $time, $tz);
createFromFormat() and PHP's DateTime::createFromFormat. The difference is that the $dt parameter can be an instance of DateTImeZone or a time zone string. And it may return a parameter exception prompt. It can be seen from the source code of createXX() that they all call the createFromFormat() method.
<?php echo Carbon::createFromFormat('Y-m-d H', '1975-05-21 22')->toDateTimeString(); // 1975-05-21 22:00:00
The last two create methods mentioned both handle Unix timestamps. The first one will return a Carbon instance equal to the expected timestamp, the time zone can be set or the default value can be selected. The second method, createFromTimestampUTC() differs from the first one in that the time zone will always be UTC(GMT). The second example of the first method is just to make the usage of this function more clear. Negative timestamps are also allowed. The
<?php echo Carbon::createFromTimestamp(-1)->toDateTimeString(); // 1969-12-31 18:59:59 echo Carbon::createFromTimestamp(-1, 'Europe/London')->toDateTimeString(); // 1970-01-01 00:59:59 echo Carbon::createFromTimeStampUTC(-1)->toDateTimeString(); // 1969-12-31 23:59:59
copy() method can copy an existing Carbon instance. Modifications to the copy-generated instance will not affect the copied object itself.
<?php $dt = Carbon::now(); echo $dt->diffInYears($dt->copy()->addYear()); // 1 // $dt was unchanged and still holds the value of Carbon:now()
Finally, if you are using a DateTime instance obtained by instantiating another library that inherits \DateTime, don't be afraid! Carbon instances can still be created extremely friendly through the following method.
<?php $dt = new \DateTime('first day of January 2008'); // <== instance from another API $carbon = Carbon::instance($dt); echo get_class($carbon); // 'Carbon\Carbon' echo $carbon->toDateTimeString(); // 2008-01-01 00:00:00
Some processing about milliseconds. The DateTime class that comes with PHP can also set milliseconds, but milliseconds are not considered when making mathematical estimates of dates. Starting from Carbon version 1.12.0, instantiation and copy can also support milliseconds like the format() method (by default, only Datetime::format() in PHP supports milliseconds).
<?php $dt = Carbon::parse('1975-05-21 22:23:00.123456'); echo $dt->micro; // 123456 echo $dt->copy()->micro; // 123456
Get the valid time value range supported by PHP: earliest time, latest time
<?php echo Carbon::maxValue(); // '2038-01-18 22:14:07' echo Carbon::minValue(); // '1901-12-13 15:45:52'
In Carbon, the formatLocalized() method calls strftime( ) method, which makes up for the defect that the underlying DateTime class in PHP does not support regional settings. If you have set the current locale by using the setlocale() method, the formatLocalized($format) method will return the set locale format.
<?php setlocale(LC_TIME, 'German'); echo $dt->formatLocalized('%A %d %B %Y'); // Mittwoch 21 Mai 1975 setlocale(LC_TIME, ''); echo $dt->formatLocalized('%A %d %B %Y'); // Wednesday 21 May 1975
The results of diffForHumans() are also converted to the regional language. Carbon's regional language can be set through the Carbon::setLocale() method.
<?php Carbon::setLocale('de'); echo Carbon::now()->addYear()->diffForHumans(); // in 1 Jahr Carbon::setLocale('en');
注意:如果在linux系统中转换出现了问题,请仔细检查安装在本地或生产系统中语言环境
locale -a 列举出所有可用的语言环境
sudo locale-gen zh_CN.utf8 安装新的语言环境
sudo dpkg-reconfigure locales 配置启用新的语言环境,并重启
通过测试方法可以得到一个模拟或真实的 Carbon 实例。只有在以下情况下,主动提供的 Carbon 实例才会被特殊处理:
$knownDate = Carbon::create(2001, 5, 21, 12); // create testing date Carbon::setTestNow($knownDate); // set the mock (of course this could be a real mock object) echo Carbon::now(); // 2001-05-21 12:00:00 echo new Carbon(); // 2001-05-21 12:00:00 echo Carbon::parse(); // 2001-05-21 12:00:00 echo new Carbon('now'); // 2001-05-21 12:00:00 echo Carbon::parse('now'); // 2001-05-21 12:00:00 var_dump(Carbon::hasTestNow()); // bool(true) Carbon::setTestNow(); // clear the mock var_dump(Carbon::hasTestNow()); // bool(false) echo Carbon::now();
有用的例子:
class SeasonalProduct { protected $price; public function __construct($price) { $this->price = $price; } public function getPrice() { $multiplier = 1; if (Carbon::now()->month == 12) { $multiplier = 2; } return $this->price * $multiplier; } } $product = new SeasonalProduct(100); Carbon::setTestNow(Carbon::parse('first day of March 2000')); echo $product->getPrice(); // 100 Carbon::setTestNow(Carbon::parse('first day of December 2000')); echo $product->getPrice(); // 200 Carbon::setTestNow(Carbon::parse('first day of May 2000')); echo $product->getPrice(); // 100 Carbon::setTestNow();
一些相关的用法也可以得到一个模拟的 now 实例,返回相应的模拟数据。
$knownDate = Carbon::create(2001, 5, 21, 12); // create testing date Carbon::setTestNow($knownDate); // set the mock echo new Carbon('tomorrow'); // 2001-05-22 00:00:00 ... notice the time ! echo new Carbon('yesterday'); // 2001-05-20 00:00:00 echo new Carbon('next wednesday'); // 2001-05-23 00:00:00 echo new Carbon('last friday'); // 2001-05-18 00:00:00 echo new Carbon('this thursday'); // 2001-05-24 00:00:00 Carbon::setTestNow();
以下是当前支持的时间转换字
值得注意的是像 next() , previous() 和 modify() 方法等相关的修改会把日期的时间部分设置成 00:00:00 。
获取器通过PHP的 __get() 方式实现。可以直接通过一下方式直接获取到属性的值。
$dt = Carbon::parse('2012-9-5 23:26:11.123789'); // These getters specifically return integers, ie intval() var_dump($dt->year); // int(2012) var_dump($dt->month); // int(9) var_dump($dt->day); // int(5) var_dump($dt->hour); // int(23) var_dump($dt->minute); // int(26) var_dump($dt->second); // int(11) var_dump($dt->micro); // int(123789) var_dump($dt->dayOfWeek); // int(3) var_dump($dt->dayOfYear); // int(248) var_dump($dt->weekOfMonth); // int(1) var_dump($dt->weekOfYear); // int(36) var_dump($dt->daysInMonth); // int(30) var_dump($dt->timestamp); // int(1346901971) var_dump(Carbon::createFromDate(1975, 5, 21)->age); // int(41) calculated vs now in the same tz var_dump($dt->quarter); // int(3) // Returns an int of seconds difference from UTC (+/- sign included) var_dump(Carbon::createFromTimestampUTC(0)->offset); // int(0) var_dump(Carbon::createFromTimestamp(0)->offset); // int(-18000) // Returns an int of hours difference from UTC (+/- sign included) var_dump(Carbon::createFromTimestamp(0)->offsetHours); // int(-5) // Indicates if day light savings time is on var_dump(Carbon::createFromDate(2012, 1, 1)->dst); // bool(false) var_dump(Carbon::createFromDate(2012, 9, 1)->dst); // bool(true) // Indicates if the instance is in the same timezone as the local timezone var_dump(Carbon::now()->local); // bool(true) var_dump(Carbon::now('America/Vancouver')->local); // bool(false) // Indicates if the instance is in the UTC timezone var_dump(Carbon::now()->utc); // bool(false) var_dump(Carbon::now('Europe/London')->utc); // bool(false) var_dump(Carbon::createFromTimestampUTC(0)->utc); // bool(true) // Gets the DateTimeZone instance echo get_class(Carbon::now()->timezone); // DateTimeZone echo get_class(Carbon::now()->tz); // DateTimeZone // Gets the DateTimeZone instance name, shortcut for ->timezone->getName() echo Carbon::now()->timezoneName; // America/Toronto echo Carbon::now()->tzName; // America/Toronto
Setters 通过PHP的 __set() 方法实现。值得注意的是,通过这种方式设置时间戳时,时区不会相对于时间戳而改变。如果需要改变时区的话,需要针对时区单独设置。
$dt = Carbon::now(); $dt->year = 1975; $dt->month = 13; // would force year++ and month = 1 $dt->month = 5; $dt->day = 21; $dt->hour = 22; $dt->minute = 32; $dt->second = 5; $dt->timestamp = 169957925; // This will not change the timezone // Set the timezone via DateTimeZone instance or string $dt->timezone = new DateTimeZone('Europe/London'); $dt->timezone = 'Europe/London'; $dt->tz = 'Europe/London';
此处 Setters 方法的参数是必选参数,Carbon 提供了更多种设置方式可供使用。值得注意的是,所有对于时区的修改都会影响整个到 Carbon 实例。对时间戳进行修改时不会自动转换到时间戳对应的时区。
$dt = Carbon::now(); $dt->year(1975)->month(5)->day(21)->hour(22)->minute(32)->second(5)->toDateTimeString(); $dt->setDate(1975, 5, 21)->setTime(22, 32, 5)->toDateTimeString(); $dt->setDateTime(1975, 5, 21, 22, 32, 5)->toDateTimeString(); $dt->timestamp(169957925)->timezone('Europe/London'); $dt->tz('America/Toronto')->setTimezone('America/Vancouver');
当尝试调用 Carbon 实例的属性时,会首先检查该属性是否存在,存在返回 true,不存在返回 false。
var_dump(isset(Carbon::now()->iDoNotExist)); // bool(false) var_dump(isset(Carbon::now()->hour)); // bool(true) var_dump(empty(Carbon::now()->iDoNotExist)); // bool(true) var_dump(empty(Carbon::now()->year)); // bool(false)
(推荐教程:PHP视频教程)
The above is the detailed content of Detailed introduction to the usage of time processing class Carbon in PHP. For more information, please follow other related articles on the PHP Chinese website!