How to use the date and time class Carbon in PHP

醉折花枝作酒筹
Release: 2023-03-10 20:02:02
forward
2397 people have browsed it

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

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

Today’s date

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

Yesterday

Carbon::yesterday()->toDateString();
Copy after login

Current time

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

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

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

Laravel order data for the day

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

N days ago/after

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

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!

Related labels:
source:sunzhongwei.com
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
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!