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 a parameter, it will use the time zone from 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 parameter:
// 直接使用字符串 echo Carbon::now('Europe/London'); //2016-10-14 20:21:20 // 或者 echo Carbon::now(new DateTimeZone('Europe/London'));
except# In addition to ##now() , static functions such as
today() ,
tomorrow(),
yesterday() are also provided. However, their The time is 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 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 a 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, a valid time zone can be passed 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 whether the comparison 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 months from now
- 1 hour ago
- 5 months ago
- 1 hour later
- 5 months later
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周
Localization
可以在 app/Providers/AppServiceProvider.php 的 boot()
方法中添加下面的代码来设置全局本地化:
public function boot() { \Carbon\Carbon::setLocale('zh'); }
设置好之后,在输出时间的地方调用:
$article->created_at->diffForHumans();
类似的格式即可。
更多 Carbon 操作,可查看文档。
The above is the detailed content of Carbon, a date and time processing package in Laravel. For more information, please follow other related articles on the PHP Chinese website!

本篇文章给大家带来了关于laravel的相关知识,其中主要介绍了关于单点登录的相关问题,单点登录是指在多个应用系统中,用户只需要登录一次就可以访问所有相互信任的应用系统,下面一起来看一下,希望对大家有帮助。

本篇文章给大家带来了关于laravel的相关知识,其中主要介绍了关于Laravel的生命周期相关问题,Laravel 的生命周期从public\index.php开始,从public\index.php结束,希望对大家有帮助。

在laravel中,guard是一个用于用户认证的插件;guard的作用就是处理认证判断每一个请求,从数据库中读取数据和用户输入的对比,调用是否登录过或者允许通过的,并且Guard能非常灵活的构建一套自己的认证体系。

laravel中asset()方法的用法:1、用于引入静态文件,语法为“src="{{asset(‘需要引入的文件路径’)}}"”;2、用于给当前请求的scheme前端资源生成一个url,语法为“$url = asset('前端资源')”。

本篇文章给大家带来了关于laravel的相关知识,其中主要介绍了关于使用中间件记录用户请求日志的相关问题,包括了创建中间件、注册中间件、记录用户访问等等内容,下面一起来看一下,希望对大家有帮助。

本篇文章给大家带来了关于laravel的相关知识,其中主要介绍了关于中间件的相关问题,包括了什么是中间件、自定义中间件等等,中间件为过滤进入应用的 HTTP 请求提供了一套便利的机制,下面一起来看一下,希望对大家有帮助。

在laravel中,fill方法是一个给Eloquent实例赋值属性的方法,该方法可以理解为用于过滤前端传输过来的与模型中对应的多余字段;当调用该方法时,会先去检测当前Model的状态,根据fillable数组的设置,Model会处于不同的状态。

laravel路由文件在“routes”目录里。Laravel中所有的路由文件定义在routes目录下,它里面的内容会自动被框架加载;该目录下默认有四个路由文件用于给不同的入口使用:web.php、api.php、console.php等。


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

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

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),
