Carbon đầu tuần thứ hai

Trong hướng dẫn hôm nay, chúng tôi sẽ trình bày cách lấy dữ liệu của tuần trước trong Laravel bằng Carbon. In other words, you need to pull all the orders received in the last week. In this case, last week does not mean the last 7 days, but it’s a full week starting from Monday to Sunday. For example, if you pull the data on June 7, 2022, the last week will be May 30, 2022, to June 5, 2022

Hope you understand what we are going to achieve in this post. Instead of using raw PHP date functions, we will use we use Carbon – A simple PHP API extension for DateTime, which is inherited from the PHP DateTime class

As an illustration, we have a table filled with orders received from our valuable customers. We need to show all the orders received last week in the dashboard to make it easy for the finance team

This functions is based on Carbon date plugin that recieves 2 arguments. First argument is year and second argument is week number of the year. An array is returned based on parameters that includes start and end date

Function

function getStartAndEndDateOfWeek[$year, $week] {

        $date = Carbon::now[];
        $date->setISODate[$year, $week];
        $date->setWeekStartsAt[Carbon::MONDAY];
        $date->setWeekEndsAt[Carbon::SUNDAY];

        return [object] [
            'start_date' => $date->copy[]->startOfWeek[],
            'end_date' => $date->copy[]->endOfWeek[]
        ];
}

Calling The Function

$dates =  getStartAndEndDateOfWeek[2021, 25];

echo $dates->start_date->format['d/m/Y'];
echo $dates->end_date->format['d/m/Y'];

Output

21/06/2021
27/06/2021

Date and time manipulation is one of a few frequently-experienced challenges of developing web apps in PHP. And one of it's most prevalent issues is identifying time disparities and making them readable, such as "one hour ago"

However, handling dates and times, and issues such as this, is greatly simplified by using Carbon; it's a library which reduces lengthy hours of coding and debugging to only a few lines of code. This is because Carbon, created by Brian Nesbit, extends PHP's own DateTime class and makes it much simpler to use

If you've not heard of it before, it is self-described as

A basic PHP API extension for DateTime

In this tutorial, you will learn about Pub/Sub, a message-driven software design pattern and how to implement it in Laravel

In this article we will see how to set start day and end day of a week using carbon library in Laravel . As there are tons of methods provided by Carbon library but to set start day and end day of a week we will use startOfWeek[] and endOfWeek[] method


Controller

Write the following code on your controller to set start day of week and end day of a week


Chủ Đề