Table of Contents
1.Introduction
2.Instantiation
3.Localization
4.Testing Aids()
5.Getters
6.Setters
7.Fluent Setters
8.IsSet
Home Backend Development PHP Tutorial Detailed introduction to the usage of time processing class Carbon in PHP

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

Jul 28, 2022 pm 03:46 PM
php

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!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1664
14
PHP Tutorial
1269
29
C# Tutorial
1249
24
Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

PHP Program to Count Vowels in a String PHP Program to Count Vowels in a String Feb 07, 2025 pm 12:12 PM

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? Apr 03, 2025 am 12:03 AM

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

PHP and Python: Comparing Two Popular Programming Languages PHP and Python: Comparing Two Popular Programming Languages Apr 14, 2025 am 12:13 AM

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

PHP in Action: Real-World Examples and Applications PHP in Action: Real-World Examples and Applications Apr 14, 2025 am 12:19 AM

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

The Enduring Relevance of PHP: Is It Still Alive? The Enduring Relevance of PHP: Is It Still Alive? Apr 14, 2025 am 12:12 AM

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.

See all articles