Home  >  Article  >  Backend Development  >  PHP uses datetime processor Carbon instance method

PHP uses datetime processor Carbon instance method

小云云
小云云Original
2018-01-27 10:56:141655browse

Carbon date and time processing library can process time very conveniently. The github address is https://github.com/briannesbitt/carbon. This article mainly introduces the detailed explanation of PHP’s use of date and time processor Carbon to display time in a humanized manner. It has certain For reference value, those who are interested can learn about it. I hope it can help everyone.

Carbon can be easily installed through Composer


# composer require nesbot/carbon

The method of use is also very simple


<?php
require &#39;vendor/autoload.php&#39;;
use Carbon\Carbon;
//显示中文
Carbon::setLocale(&#39;zh&#39;);
//获取昨天的时间戳
$ts = Carbon::yesterday()->timestamp;
//人性化显示时间
echo Carbon::createFromTimestamp($ts)->diffForHumans();

The above print result was 1 day ago

How to use it in the Laravel framework

First of all, in order to display Chinese, add it in app/Providers/AppServiceProvider.php \Carbon\Carbon::setLocale('zh');To the boot() method, as follows:


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

Then you can use it. For example, in a method in ArticleController, display the publication date of the article in a humanized way. If the publication date is a timestamp, quote Carbon in the header and add the following code


use Carbon\Carbon;

Humanized publishing time


Carbon::createFromTimestamp($published_at)->diffForHumans();

In addition to humanized display time, Carbon also has many time processing functions. Please refer to the official documentation for specific usage methods.

Related recommendations:

Seven very useful Carbon methods in Laravel

Share dates in PHP Time processing tool (Carbon) example

How does Carbon determine what day of the week today is?

The above is the detailed content of PHP uses datetime processor Carbon instance method. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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