Table of Contents
操作日期/时间" >操作日期/时间
Getters and Setters" >Getters and Setters
格式化" >格式化
相对时间" >相对时间
求时间差" >求时间差
显示人类容易阅读的时间差" >显示人类容易阅读的时间差
Home Backend Development PHP Tutorial PHP date and time processing extension package worth knowing: Carbon

PHP date and time processing extension package worth knowing: Carbon

Jul 13, 2016 pm 05:05 PM
php php date time

本篇文章给大家推荐一个扩展包:Carbon,PHP date and time processing extension package worth knowing: Carbon 中日期 / 时间处理,你只需要这个扩展包就够了!

PHP date and time processing extension package worth knowing: Carbon

在 PHP date and time processing extension package worth knowing: Carbon 中使用日期和时间并不是容易或清晰的任务。我们必须处理 strtotime ,格式化问题,大量计算等等。

这个漂亮的包叫做 Carbon 可以帮助在 PHP date and time processing extension package worth knowing: Carbon 开发中处理日期/时间变得更加简单、更语义化,从而使得我们的代码更容易阅读和维护。

Carbon

Carbon 是由 Brian Nesbit 开发的一个包,它扩展了 PHP date and time processing extension package worth knowing: Carbon 自己的 DateTime 类。

PHP date and time processing extension package worth knowing: Carbon

它提供了一些很好的功能来处理 PHP date and time processing extension package worth knowing: Carbon 中的日期,特别是诸如:

  • 处理时区
  • 轻松获取当前时间
  • 将 datetime 转换成可读的内容
  • 将英语短语解析成 datetime (first day of January 2016)
  • 日期的加减 (+ 2 weeks, -6 months)
  • 处理日期的语义方法

所有的这些都带来了一个非常有用的包,使得这些在 PHP date and time processing extension package worth knowing: Carbon 中处理时间非常容易。

设置

为了使用 Carbon ,你需要从 Carbon 命名空间中导入 Carbon 。幸运的是,在 Laravel 中已经包括了 Carbon ,所以不需要和 Composer 一起添加。

当我们需要使用 Carbon 的时候,我们可以这样导入它:

<?php use Carbon\Carbon;
Copy after login

在导入之后,让我们看看我们可以用这个很棒的包做一些很酷的事情。

获取特定的日期/时间

// 获取当前时间  - 2015-12-19 10:10:54
$current = Carbon::now();
$current = new Carbon();

// 获取今天 - 2015-12-19 00:00:00
$today = Carbon::today();

// 获取昨天 - 2015-12-18 00:00:00
$yesterday = Carbon::yesterday();

// 获取明天 - 2015-12-20 00:00:00
$tomorrow = Carbon::tomorrow();

// 解析特定字符串 - 2016-01-01 00:00:00
$newYear = new Carbon(&#39;first day of January 2016&#39;);

// 设定一个特定的时区 - 2016-01-01 00:00:00
$newYearPST = new Carbon(&#39;first day of January 2016&#39;, &#39;America\Pacific&#39;);
Copy after login

除了快速定义日期/时间方法之外,Carbon 也可以让我们从特定数量的参数中创建时间。

Carbon::createFromDate($year, $month, $day, $tz);
Carbon::createFromTime($hour, $minute, $second, $tz);
Carbon::create($year, $month, $day, $hour, $minute, $second, $tz);
Copy after login

当你以一种通常不被 Carbon 识别的格式获得某种日期或时间时,这些是非常有用的。如果你为任何一个参数传递 null 值,则它默认会使用当前日期/时间传递 。

抓取日期/时间并不是你在处理日期时唯一要做的事情。你经常需要操作日期或时间。

例如,当为一个用户创建一个试用期时,你将希望试用期在一定时间后过期。假设我们有 30 天的试用期。我们可以用 addsubtract 很容易的计算出时间。

在这段试用期内,我们会:

// 获取当前时间
$current = Carbon::now();

// 添加 30 天到当前时间
$trialExpires = $current->addDays(30);
Copy after login

从 Carbon 文档 中,我们可以找到一些其他的 add()sub() 方法:

$dt = Carbon::create(2012, 1, 31, 0);

echo $dt->toDateTimeString();            // 2012-01-31 00:00:00

echo $dt->addYears(5);                   // 2017-01-31 00:00:00
echo $dt->addYear();                     // 2018-01-31 00:00:00
echo $dt->subYear();                     // 2017-01-31 00:00:00
echo $dt->subYears(5);                   // 2012-01-31 00:00:00

echo $dt->addMonths(60);                 // 2017-01-31 00:00:00
echo $dt->addMonth();                    // 2017-03-03 00:00:00 equivalent of $dt->month($dt->month + 1); so it wraps
echo $dt->subMonth();                    // 2017-02-03 00:00:00
echo $dt->subMonths(60);                 // 2012-02-03 00:00:00

echo $dt->addDays(29);                   // 2012-03-03 00:00:00
echo $dt->addDay();                      // 2012-03-04 00:00:00
echo $dt->subDay();                      // 2012-03-03 00:00:00
echo $dt->subDays(29);                   // 2012-02-03 00:00:00

echo $dt->addWeekdays(4);                // 2012-02-09 00:00:00
echo $dt->addWeekday();                  // 2012-02-10 00:00:00
echo $dt->subWeekday();                  // 2012-02-09 00:00:00
echo $dt->subWeekdays(4);                // 2012-02-03 00:00:00

echo $dt->addWeeks(3);                   // 2012-02-24 00:00:00
echo $dt->addWeek();                     // 2012-03-02 00:00:00
echo $dt->subWeek();                     // 2012-02-24 00:00:00
echo $dt->subWeeks(3);                   // 2012-02-03 00:00:00

echo $dt->addHours(24);                  // 2012-02-04 00:00:00
echo $dt->addHour();                     // 2012-02-04 01:00:00
echo $dt->subHour();                     // 2012-02-04 00:00:00
echo $dt->subHours(24);                  // 2012-02-03 00:00:00

echo $dt->addMinutes(61);                // 2012-02-03 01:01:00
echo $dt->addMinute();                   // 2012-02-03 01:02:00
echo $dt->subMinute();                   // 2012-02-03 01:01:00
echo $dt->subMinutes(61);                // 2012-02-03 00:00:00

echo $dt->addSeconds(61);                // 2012-02-03 00:01:01
echo $dt->addSecond();                   // 2012-02-03 00:01:02
echo $dt->subSecond();                   // 2012-02-03 00:01:01
echo $dt->subSeconds(61);                // 2012-02-03 00:00:00
Copy after login

另外一种快速操作或读取时间的方法是使用可用的 getters 和 setters 。

$dt = Carbon::now();

// 设置一些参数
$dt->year   = 2015;
$dt->month  = 04;
$dt->day    = 21;
$dt->hour   = 22;
$dt->minute = 32;
$dt->second = 5;

// 获取一些参数
var_dump($dt->year);
var_dump($dt->month);
var_dump($dt->day);
var_dump($dt->hour);
var_dump($dt->second);
var_dump($dt->dayOfWeek);
var_dump($dt->dayOfYear);
var_dump($dt->weekOfMonth);
var_dump($dt->daysInMonth);
Copy after login

我们甚至还可以把一些 setter 串在一起。

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

在上面的示例中,你可能注意到了 ->toDateTimeString() 方法。我们可以方便的为达到我们的目的去进行格式化。在这种情况下,我们得到了一个日期时间字符串。

$dt = Carbon::now();

echo $dt->toDateString();               // 2015-12-19
echo $dt->toFormattedDateString();      // Dec 19, 2015
echo $dt->toTimeString();               // 10:10:16
echo $dt->toDateTimeString();           // 2015-12-19 10:10:16
echo $dt->toDayDateTimeString();        // Sat, Dec 19, 2015 10:10 AM

// ……当然 format() 也可以这样用
echo $dt->format(&#39;l jS \\of F Y h:i:s A&#39;);         // Saturday 19th of December 2015 10:10:16 AM
Copy after login

通过 diff() 方法可以很容易的显示相对时间。

例如,我们有一篇博客,并且我们想显示它是在 三小时 前发布的。可以利用这些方法。

这些方法用于求两个时间的时间差。

$current = Carbon::now();
$dt      = Carbon::now();

$dt = $dt->subHours(6);
echo $dt->diffInHours($current, false);  // 6,相当于 $current-$dt,这里的false表示结果不取绝对值,默认是值是true
echo $current->diffInHours($dt, false);  // -6,相当于 $dt-$current

$future = $current->addMonth();
$past   = $current->subMonths(2);
echo $current->diffInDays($future);      // 31
echo $current->diffInDays($past);        // -62
Copy after login

在过去的几年,显示相对时间变得越来越流行。在 Twitter 和 Facebook 等社交网络中经常可以看到。

例如,将时间显示为 3 小时前 比显示 上午 8:12,更适合人类阅读。

这些方法被用于计算时间差,并转换为人类可阅读的格式。

这里有四种表达时间差的方式:

  • 将一个过去的时间和现在做比较:
    • 1 小时前
    • 5 个月前
  • 将一个未来的时间和现在做比较:
    • 1 小时后
    • 5 个月后
  • 将一个过去的时间和另一个时间做比较:
    • 1 小时前
    • 5 小时前
  • 将一个未来的时间和另一个做比较:
    • 1 小时后
    • 5 小时后
$dt     = Carbon::now();
$past   = $dt->subMonth();
$future = $dt->addMonth();

echo $dt->subDays(10)->diffForHumans();     // 10 天前
echo $dt->diffForHumans($past);             // 1 个月前
echo $dt->diffForHumans($future);           // 1 个月前
Copy after login

总结

Carbon 能做的远远不止这些。请务必查看 Carbon 官方文档。希望这能帮助你在 PHP date and time processing extension package worth knowing: Carbon 中更容易的使用日期 / 时间并加快开发效率!

推荐学习:《PHP date and time processing extension package worth knowing: Carbon视频教程

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 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
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
1666
14
PHP Tutorial
1273
29
C# Tutorial
1252
24
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: 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

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 vs. Python: Understanding the Differences PHP vs. Python: Understanding the Differences Apr 11, 2025 am 12:15 AM

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

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.

PHP and Python: Code Examples and Comparison PHP and Python: Code Examples and Comparison Apr 15, 2025 am 12:07 AM

PHP and Python have their own advantages and disadvantages, and the choice depends on project needs and personal preferences. 1.PHP is suitable for rapid development and maintenance of large-scale web applications. 2. Python dominates the field of data science and machine learning.

PHP vs. Other Languages: A Comparison PHP vs. Other Languages: A Comparison Apr 13, 2025 am 12:19 AM

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP and Python: Different Paradigms Explained PHP and Python: Different Paradigms Explained Apr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

See all articles