Home Backend Development PHP Tutorial Examples of how to use date and time processing package Carbon in Laravel

Examples of how to use date and time processing package Carbon in Laravel

Sep 23, 2017 am 09:27 AM
laravel date time

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

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

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

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

If you want to use a different time zone, you need to pass a valid time zone as the argument:


// 直接使用字符串
echo Carbon::now(&#39;Europe/London&#39;); //2016-10-14 20:21:20
// 或者
echo Carbon::now(new DateTimeZone(&#39;Europe/London&#39;));
Copy after login

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(&#39;Europe/London&#39;);       // 2016-10-14 00:00:00
echo Carbon::yesterday();       // 2016-10-14 00:00:00
Copy after login

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

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

Convert date type to string

As mentioned above, by default, Carbon's method returns a date and time object. Although it is an object, you can directly use echo to output the result because of the __toString magic method. But if you want to convert it to a string, you can use the toDateString or toDateTimeString method:


echo Carbon::now()->toDateString(); //2016-10-14
echo Carbon::now()->toDateTimeString(); //2016-10-14 20:22:50
Copy after login

Date parsing

You can also use the parse method to parse dates of any order and type (the result is a Carbon type date-time object):


echo Carbon::parse(&#39;2016-10-15&#39;)->toDateTimeString(); //2016-10-15 00:00:00
echo Carbon::parse(&#39;2016-10-15&#39;)->toDateTimeString(); //2016-10-15 00:00:00
echo Carbon::parse(&#39;2016-10-15 00:10:25&#39;)->toDateTimeString(); //2016-10-15 00:10:25
 
echo Carbon::parse(&#39;today&#39;)->toDateTimeString(); //2016-10-15 00:00:00
echo Carbon::parse(&#39;yesterday&#39;)->toDateTimeString(); //2016-10-14 00:00:00
echo Carbon::parse(&#39;tomorrow&#39;)->toDateTimeString(); //2016-10-16 00:00:00
echo Carbon::parse(&#39;2 days ago&#39;)->toDateTimeString(); //2016-10-13 20:49:53
echo Carbon::parse(&#39;+3 days&#39;)->toDateTimeString(); //2016-10-18 20:49:53
echo Carbon::parse(&#39;+2 weeks&#39;)->toDateTimeString(); //2016-10-29 20:49:53
echo Carbon::parse(&#39;+4 months&#39;)->toDateTimeString(); //2017-02-15 20:49:53
echo Carbon::parse(&#39;-1 year&#39;)->toDateTimeString(); //2015-10-15 20:49:53
echo Carbon::parse(&#39;next wednesday&#39;)->toDateTimeString(); //2016-10-19 00:00:00
echo Carbon::parse(&#39;last friday&#39;)->toDateTimeString(); //2016-10-14 00:00:00
Copy after login

Constructing date

You can also construct the date using separate year, month and day:


$year = &#39;2015&#39;;
$month = &#39;04&#39;;
$day = &#39;12&#39;;
 
echo Carbon::createFromDate($year, $month, $day); //2015-04-12 20:55:59
 
$hour = &#39;02&#39;;
$minute = &#39;15&#39;:
$second = &#39;30&#39;;
 
echo Carbon::create($year, $month, $day, $hour, $minute, $second); //2015-04-12 02:15:30
 
echo Carbon::createFromDate(null, 12, 25); // 年默认为当前年份
Copy after login

Additionally, you can pass a valid time zone as the last parameter .

Date Operations

Date operations can be done by adding (increasing) or sub (subtracting) followed by the unit to be added or subtracted. For example, if you want to add a specified number of days to a date, you can use the addDays method. In addition, a modify method is provided. The parameter format is + or - followed by the value and unit. So, if you want to add a year to the current date, you can pass +1 year:


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(&#39;+15 days&#39;); //2016-10-30 14:00:01
echo Carbon::now()->modify(&#39;-2 days&#39;); //2016-10-13 14:00:01
Copy after login

Date comparison

In Carbon you can use the following methods to compare dates:

  • 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, &#39;America/Vancouver&#39;);
 
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 &#39;America/Vancouver&#39;
 
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)
Copy after login

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

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

diffForHumans

"One month ago" is easier to read than "30 days ago", and many date libraries provide this common function , after the date is parsed, there are four possibilities:

1. When the compared time exceeds the current default time


  • 1 days ago

  • 5 months ago

2. When comparing the future time with the current default time


  • 1 hour from now

  • 5 month from now

3. When the compared value exceeds another value


  • 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周
Copy after login

本地化

可以在 app/Providers/AppServiceProvider.php 的 boot() 方法中添加下面的代码来设置全局本地化:


public function boot()
{
  \Carbon\Carbon::setLocale(&#39;zh&#39;);
}
Copy after login

设置好之后,在输出时间的地方调用:


$article->created_at->diffForHumans();
Copy after login

类似的格式即可。

更多 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!

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 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)

Comparison of the latest versions of Laravel and CodeIgniter Comparison of the latest versions of Laravel and CodeIgniter Jun 05, 2024 pm 05:29 PM

The latest versions of Laravel 9 and CodeIgniter 4 provide updated features and improvements. Laravel9 adopts MVC architecture and provides functions such as database migration, authentication and template engine. CodeIgniter4 uses HMVC architecture to provide routing, ORM and caching. In terms of performance, Laravel9's service provider-based design pattern and CodeIgniter4's lightweight framework give it excellent performance. In practical applications, Laravel9 is suitable for complex projects that require flexibility and powerful functions, while CodeIgniter4 is suitable for rapid development and small applications.

How do the data processing capabilities in Laravel and CodeIgniter compare? How do the data processing capabilities in Laravel and CodeIgniter compare? Jun 01, 2024 pm 01:34 PM

Compare the data processing capabilities of Laravel and CodeIgniter: ORM: Laravel uses EloquentORM, which provides class-object relational mapping, while CodeIgniter uses ActiveRecord to represent the database model as a subclass of PHP classes. Query builder: Laravel has a flexible chained query API, while CodeIgniter’s query builder is simpler and array-based. Data validation: Laravel provides a Validator class that supports custom validation rules, while CodeIgniter has less built-in validation functions and requires manual coding of custom rules. Practical case: User registration example shows Lar

Laravel - Artisan Commands Laravel - Artisan Commands Aug 27, 2024 am 10:51 AM

Laravel - Artisan Commands - Laravel 5.7 comes with new way of treating and testing new commands. It includes a new feature of testing artisan commands and the demonstration is mentioned below ?

Which one is more beginner-friendly, Laravel or CodeIgniter? Which one is more beginner-friendly, Laravel or CodeIgniter? Jun 05, 2024 pm 07:50 PM

For beginners, CodeIgniter has a gentler learning curve and fewer features, but covers basic needs. Laravel offers a wider feature set but has a slightly steeper learning curve. In terms of performance, both Laravel and CodeIgniter perform well. Laravel has more extensive documentation and active community support, while CodeIgniter is simpler, lightweight, and has strong security features. In the practical case of building a blogging application, Laravel's EloquentORM simplifies data manipulation, while CodeIgniter requires more manual configuration.

Laravel vs CodeIgniter: Which framework is better for large projects? Laravel vs CodeIgniter: Which framework is better for large projects? Jun 04, 2024 am 09:09 AM

When choosing a framework for large projects, Laravel and CodeIgniter each have their own advantages. Laravel is designed for enterprise-level applications, offering modular design, dependency injection, and a powerful feature set. CodeIgniter is a lightweight framework more suitable for small to medium-sized projects, emphasizing speed and ease of use. For large projects with complex requirements and a large number of users, Laravel's power and scalability are more suitable. For simple projects or situations with limited resources, CodeIgniter's lightweight and rapid development capabilities are more ideal.

Questions and Answers on PHP Enterprise Application Microservice Architecture Design Questions and Answers on PHP Enterprise Application Microservice Architecture Design May 07, 2024 am 09:36 AM

Microservice architecture uses PHP frameworks (such as Symfony and Laravel) to implement microservices and follows RESTful principles and standard data formats to design APIs. Microservices communicate via message queues, HTTP requests, or gRPC, and use tools such as Prometheus and ELKStack for monitoring and troubleshooting.

Laravel vs CodeIgniter: Which framework is better for small projects? Laravel vs CodeIgniter: Which framework is better for small projects? Jun 04, 2024 pm 05:29 PM

For small projects, Laravel is suitable for larger projects that require strong functionality and security. CodeIgniter is suitable for very small projects that require lightweight and ease of use.

Which is the better template engine, Laravel or CodeIgniter? Which is the better template engine, Laravel or CodeIgniter? Jun 03, 2024 am 11:30 AM

Comparing Laravel's Blade and CodeIgniter's Twig template engine, choose based on project needs and personal preferences: Blade is based on MVC syntax, which encourages good code organization and template inheritance. Twig is a third-party library that provides flexible syntax, powerful filters, extended support, and security sandboxing.

See all articles