An example of how PHP uses the date and time processor Carbon to display humanized time

黄舟
Release: 2023-03-14 21:16:01
Original
1715 people have browsed it

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 reference value. If you are interested, you can learn more

This article introduces the use of PHP's date and time processor Carbon Humanized time display, share it with everyone, the details are as follows:

Carbon date and time processing library can process time very conveniently,

can be easily installed through Composer Carbon

# composer require nesbot/carbon
Copy after login

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

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 \Carbon\Carbon::setLocale('zh'); to boot() method in app/Providers/AppServiceProvider.php, As follows:

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

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

use Carbon\Carbon;
Copy after login

Humanized publishing time

Carbon::createFromTimestamp($published_at)->diffForHumans();
Copy after login

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

The above is the detailed content of An example of how PHP uses the date and time processor Carbon to display humanized time. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template