Home >Backend Development >PHP Problem >How to use the date and time class Carbon in PHP

How to use the date and time class Carbon in PHP

醉折花枝作酒筹
醉折花枝作酒筹forward
2021-06-23 16:13:452517browse

Carbon is PHP's date processing class library. Carbon inherits PHP's Datetime class, so methods that are not involved in Carbon but have been implemented in Datetime can be used. The following is an introduction to the date processing class library. Friends who need it can refer to it.

How to use the date and time class Carbon in PHP

Carbon inherits the PHP DateTime class, so the methods of the DateTime class are also applicable to the Carbon class.

Initialize a date

use Carbon\Carbon;
$today = new Carbon('2018-08-01');

The first day of this month, the first day of last month

$first_day = new Carbon('first day of this month');
$first_day = new Carbon('first day of last month');
return $month->format('Y-m');   // 2018-08

Today’s date

echo Carbon::today()->toDateString();// 2018-09-10

Yesterday

Carbon::yesterday()->toDateString();

Current time

Carbon::now();             // 2018-10-08 14:24:15.074542 Asia/Shanghai (+08:00)
echo Carbon::now();    // 2018-10-08 14:28:10

Time difference

$start  = new Carbon('2018-10-04 15:00:03');
$end    = new Carbon('2018-10-05 17:00:09');
$start->diff($end)->format('%H:%I:%S');
02:00:06

Sometime today/Sometime yesterday

>>> Carbon::parse('today 8am');
=> Carbon\Carbon @1563148800 {#3955
     date: 2019-07-15 08:00:00.0 Asia/Shanghai (+08:00),
   }
>>> Carbon::parse('yesterday 6pm');
=> Carbon\Carbon @1563098400 {#3954
     date: 2019-07-14 18:00:00.0 Asia/Shanghai (+08:00),
   }

Laravel order data for the day

$orders = Order::whereDate('created_at', Carbon::today())->get();

N days ago/after

date("Ymd", strtotime("+7 day"));    // "20190716"
date("Ymd", strtotime("-7 day"));

Recommended learning: php video tutorial

The above is the detailed content of How to use the date and time class Carbon in PHP. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:sunzhongwei.com. If there is any infringement, please contact admin@php.cn delete