


Examples of how to use date and time processing package Carbon in Laravel
There are many things to consider when processing dates and times, such as date format, time zone, leap year, and months with different days. It is too easy to make mistakes by yourself. The following article mainly introduces you to date and time processing in Laravel. Friends who need the simple use of Carbon can refer to it.
Preface
We all often need to deal with dates and times when writing PHP applications. This article will take you to learn about Carbon - inherited from An API extension to the PHP DateTime class that makes working with dates and times easier.
The default time processing class used in Laravel is Carbon.
<?php namespace Carbon; class Carbon extends \DateTime { // code here }
You can see the code snippet declared above in the Carbon class in the Carbon namespace.
Installation
Carbon can be installed through Composer:
composer require nesbot/carbon
PS: Since the Laravel project has installed this package by default, there is no need to execute the above command again.
Using
You need to import Carbon through the namespace to use it, without providing the full name every time.
use Carbon\Carbon;
Get the current time
You can get the current date and time with the now() method. If you don't specify an argument, it will use the time zone in the PHP configuration:
<?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 argument:
// 直接使用字符串 echo Carbon::now('Europe/London'); //2016-10-14 20:21:20 // 或者 echo Carbon::now(new DateTimeZone('Europe/London'));
In addition to now()
, it also provides today()
, tomorrow()
, yesterday()
and other static functions, however, their times are all 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:00The above output result is actually a Carbon Type of date and time object:
Carbon {#179 ▼ +"date": "2016-06-14 00:00:00.000000" +"timezone_type": 3 +"timezone": "UTC" }To get the date of string type, you can use the following code:
echo Carbon::today()->toDateTimeString(); echo Carbon::yesterday()->toDateTimeString(); echo Carbon::tomorrow()->toDateTimeString();
Convert date type to string
echo Carbon::now()->toDateString(); //2016-10-14 echo Carbon::now()->toDateTimeString(); //2016-10-14 20:22:50
Date parsing
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
Constructing 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); // 年默认为当前年份Additionally, you can pass a valid time zone as the last parameter .
Date Operations
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
- min – Returns the minimum date.
- max – Returns the maximum date.
- eq – Determines whether two dates are equal.
- gt – Determines whether the first date is greater than the second date.
- lt – Determines 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 – Determines 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 the comparison. Whether they can be equal, the default 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, some auxiliary methods are provided, you can understand their meaning 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
- 1 days ago
- 5 months ago
- 1 hour from now
- 5 month from now
- 1 hour ago
- 5 months ago
4、当比较的值在另一个值之后
1小时后
5月后
你可以把第二个参数设置为 true 来删除“前”、“距现在”等修饰语:diffForHumans(Carbon $other, true)
。
echo Carbon::now()->subDays(5)->diffForHumans(); // 5天前 echo Carbon::now()->diffForHumans(Carbon::now()->subYear()); // 1年后 $dt = Carbon::createFromDate(2011, 8, 1); echo $dt->diffForHumans($dt->copy()->addMonth()); // 1月前 echo $dt->diffForHumans($dt->copy()->subMonth()); // 11月后 echo Carbon::now()->addSeconds(5)->diffForHumans(); // 5秒距现在 echo Carbon::now()->subDays(24)->diffForHumans(); // 3周前 echo Carbon::now()->subDays(24)->diffForHumans(null, true); // 3周
本地化
可以在 app/Providers/AppServiceProvider.php 的 boot()
方法中添加下面的代码来设置全局本地化:
public function boot() { \Carbon\Carbon::setLocale('zh'); }
设置好之后,在输出时间的地方调用:
$article->created_at->diffForHumans();
类似的格式即可。
更多 Carbon 操作,可查看文档。
总结
The above is the detailed content of Examples of how to use date and time processing package Carbon in Laravel. For more information, please follow other related articles on the PHP Chinese website!

PHP remains important in modern web development, especially in content management and e-commerce platforms. 1) PHP has a rich ecosystem and strong framework support, such as Laravel and Symfony. 2) Performance optimization can be achieved through OPcache and Nginx. 3) PHP8.0 introduces JIT compiler to improve performance. 4) Cloud-native applications are deployed through Docker and Kubernetes to improve flexibility and scalability.

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 each have their own advantages and are suitable for different scenarios. 1.PHP is suitable for web development and provides built-in web servers and rich function libraries. 2. Python is suitable for data science and machine learning, with concise syntax and a powerful standard library. When choosing, it should be decided based on project requirements.

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 reasons why PHP is the preferred technology stack for many websites include its ease of use, strong community support, and widespread use. 1) Easy to learn and use, suitable for beginners. 2) Have a huge developer community and rich resources. 3) Widely used in WordPress, Drupal and other platforms. 4) Integrate tightly with web servers to simplify development deployment.

PHP remains a powerful and widely used tool in modern programming, especially in the field of web development. 1) PHP is easy to use and seamlessly integrated with databases, and is the first choice for many developers. 2) It supports dynamic content generation and object-oriented programming, suitable for quickly creating and maintaining websites. 3) PHP's performance can be improved by caching and optimizing database queries, and its extensive community and rich ecosystem make it still important in today's technology stack.

In PHP, weak references are implemented through the WeakReference class and will not prevent the garbage collector from reclaiming objects. Weak references are suitable for scenarios such as caching systems and event listeners. It should be noted that it cannot guarantee the survival of objects and that garbage collection may be delayed.

The \_\_invoke method allows objects to be called like functions. 1. Define the \_\_invoke method so that the object can be called. 2. When using the $obj(...) syntax, PHP will execute the \_\_invoke method. 3. Suitable for scenarios such as logging and calculator, improving code flexibility and readability.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SublimeText3 Mac version
God-level code editing software (SublimeText3)