Detailed introduction to the usage of time processing class Carbon in PHP

WBOY
Release: 2023-04-11 07:18:01
forward
5226 people have browsed it

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.

Detailed introduction to the usage of time processing class Carbon in PHP

(Recommended tutorial: PHP video tutorial)

1.Introduction

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
}
Copy after login

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;
Copy after login

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, &#39;America/Toronto&#39;);
$dtVancouver = Carbon::createFromDate(2012, 1, 1, &#39;America/Vancouver&#39;);
 
echo $dtVancouver->diffInHours($dtToronto); // 3
Copy after login

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.

2.Instantiation

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(&#39;first day of January 2008&#39;, &#39;America/Vancouver&#39;);
echo get_class($carbon);                 // &#39;Carbon\Carbon&#39;
$carbon = Carbon::now(-5);
Copy after login

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(&#39;Europe/London&#39;));
 
// or just pass the timezone as a string
$nowInLondonTz = Carbon::now(&#39;Europe/London&#39;);
 
// 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
Copy after login

You will like using the parse() method to replace the original cumbersome construction method

<?php
echo (new Carbon(&#39;first day of December 2008&#39;))->addWeeks(2);     // 2008-12-15 00:00:00
echo Carbon::parse(&#39;first day of December 2008&#39;)->addWeeks(2);    // 2008-12-15 00:00:00
Copy after login

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(&#39;Europe/London&#39;);
echo $tomorrow;                          // 2016-06-25 00:00:00
$yesterday = Carbon::yesterday();
echo $yesterday;                         // 2016-06-23 00:00:00
Copy after login

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);
Copy after login

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, &#39;Europe/London&#39;);
 
// A two digit minute could not be found
try { 
    Carbon::create(1975, 5, 21, 22, -2, 0); 
} catch(InvalidArgumentException $x) { 
    echo $x->getMessage(); 
}
Copy after login
<?php
Carbon::createFromFormat($format, $time, $tz);
Copy after login

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(&#39;Y-m-d H&#39;, &#39;1975-05-21 22&#39;)->toDateTimeString(); // 1975-05-21 22:00:00
Copy after login

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, &#39;Europe/London&#39;)->toDateTimeString();       // 1970-01-01 00:59:59
echo Carbon::createFromTimeStampUTC(-1)->toDateTimeString();                     // 1969-12-31 23:59:59
Copy after login

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()
Copy after login

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(&#39;first day of January 2008&#39;); // <== instance from another API
$carbon = Carbon::instance($dt);
echo get_class($carbon);                               // &#39;Carbon\Carbon&#39;
echo $carbon->toDateTimeString();                      // 2008-01-01 00:00:00
Copy after login

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(&#39;1975-05-21 22:23:00.123456&#39;);
echo $dt->micro;                                       // 123456
echo $dt->copy()->micro;                               // 123456
Copy after login

Get the valid time value range supported by PHP: earliest time, latest time

<?php
echo Carbon::maxValue();                               // &#39;2038-01-18 22:14:07&#39;
echo Carbon::minValue();                               // &#39;1901-12-13 15:45:52&#39;
Copy after login

3.Localization

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, &#39;German&#39;);
echo $dt->formatLocalized(&#39;%A %d %B %Y&#39;);          // Mittwoch 21 Mai 1975
setlocale(LC_TIME, &#39;&#39;);
echo $dt->formatLocalized(&#39;%A %d %B %Y&#39;);          // Wednesday 21 May 1975
Copy after login

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(&#39;de&#39;);
echo Carbon::now()->addYear()->diffForHumans();    // in 1 Jahr
 
Carbon::setLocale(&#39;en&#39;);
Copy after login

注意:如果在linux系统中转换出现了问题,请仔细检查安装在本地或生产系统中语言环境

locale -a 列举出所有可用的语言环境

sudo locale-gen zh_CN.utf8 安装新的语言环境

sudo dpkg-reconfigure locales 配置启用新的语言环境,并重启

4.Testing Aids()

通过测试方法可以得到一个模拟或真实的 Carbon 实例。只有在以下情况下,主动提供的 Carbon 实例才会被特殊处理:

  • 调用静态方法 now(),例如:Carbon::now()
  • 传给 construct 或 parse() 方法的是 null (或空字符串),例如:new Carbon(null)
  • 当传给 construct 或 parse()的是字符串 now,例如:new Carbon(‘now’)
$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(&#39;now&#39;);                                // 2001-05-21 12:00:00
echo Carbon::parse(&#39;now&#39;);                             // 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();
Copy after login

有用的例子:

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(&#39;first day of March 2000&#39;));
echo $product->getPrice();                                             // 100
Carbon::setTestNow(Carbon::parse(&#39;first day of December 2000&#39;));
echo $product->getPrice();                                             // 200
Carbon::setTestNow(Carbon::parse(&#39;first day of May 2000&#39;));
echo $product->getPrice();                                             // 100
Carbon::setTestNow();
Copy after login

一些相关的用法也可以得到一个模拟的 now 实例,返回相应的模拟数据。

$knownDate = Carbon::create(2001, 5, 21, 12);          // create testing date
Carbon::setTestNow($knownDate);                        // set the mock
echo new Carbon(&#39;tomorrow&#39;);                           // 2001-05-22 00:00:00  ... notice the time !
echo new Carbon(&#39;yesterday&#39;);                          // 2001-05-20 00:00:00
echo new Carbon(&#39;next wednesday&#39;);                     // 2001-05-23 00:00:00
echo new Carbon(&#39;last friday&#39;);                        // 2001-05-18 00:00:00
echo new Carbon(&#39;this thursday&#39;);                      // 2001-05-24 00:00:00
Carbon::setTestNow();
Copy after login

以下是当前支持的时间转换字

  • this
  • last
  • next
  • tomorrow
  • yesterday
  • +
  • -
  • first
  • ago

值得注意的是像 next() , previous() 和 modify() 方法等相关的修改会把日期的时间部分设置成 00:00:00 。

5.Getters

获取器通过PHP的 __get() 方式实现。可以直接通过一下方式直接获取到属性的值。

$dt = Carbon::parse(&#39;2012-9-5 23:26:11.123789&#39;);
 
// 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(&#39;America/Vancouver&#39;)->local);           // bool(false)
 
// Indicates if the instance is in the UTC timezone
var_dump(Carbon::now()->utc);                                // bool(false)
var_dump(Carbon::now(&#39;Europe/London&#39;)->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
Copy after login

6.Setters

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(&#39;Europe/London&#39;);
$dt->timezone = &#39;Europe/London&#39;;
$dt->tz = &#39;Europe/London&#39;;
Copy after login

7.Fluent Setters

此处 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(&#39;Europe/London&#39;);
 
$dt->tz(&#39;America/Toronto&#39;)->setTimezone(&#39;America/Vancouver&#39;);
Copy after login

8.IsSet

当尝试调用 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)
Copy after login

(推荐教程: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!

Related labels:
php
source:jb51.net
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!