Get First day of last month timestamp with Carbon - laravel-5

I want to get the timestamp in milliseconds for first day of last month and last day of last month using Carbon in laravel.
I have tried to do it with carbon::parse, which is achieved. But I want to instantiate the Carbon class simply to achieve the same.
This is the code that works fine with Carbon::parse
Carbon::parse('first day of last month',$timezone)->timestamp
But I want to achieve the same using something like below.
$start = new Carbon('first day of last month');
$end = new Carbon('last day of last month');
The output should be timestamp in milliseconds. Like 1555704794000

You may try the below code
$previous_month_start = Carbon::now()->subMonth()->startOfMonth()->format('x');
$previous_month_end = Carbon::now()->subMonth()->endOfMonth()->format('x');

Related

Carbon: comparing date instances is giving unexpected result

This problem is driving me crazy.
Here is my Carbon instance:
$carbonTemp = CarbonImmutable::createFromFormat('Y-m-d', $date);
What I want to do is just to understand if the date here is the last day of the week.
$carbonTemp->equalTo($carbonTemp->endOfWeek())
If $date = '2021-08-08' which is the last day of this week, the result above must be true, right?
It is giving me FALSE !!
Even though $carbonTemp->endOfWeek()->format('Y-m-d') is giving me '2021-08-08'.
endOfWeek() returns last day of week and time 23:59:59.999999. Therefore it is necessary to use endOfDay() method when creating date.
$carbonTemp = CarbonImmutable::createFromFormat('Y-m-d', $date)->endOfDay();
that's because you created CarbonImmutable object, so endOfWeek will not work.
Create a normal Carbon date:
$carbonTemp = Carbon::createFromFormat('Y-m-d', $date);

Getting records for the previous calendar month

I am trying to get the records of the previous month. That is say we are in February - I'd want to get records from 1st January to 31st January.
I tried:
$approved_reviews_lastMonth = ReviewHeader::where('created_at', '=', Carbon::now()->subMonth(1))->count();
But this does not get any for the last month.
Anyone?
Use format() to get the Year-Month format, and use like to get the previous month count.
$approved_reviews_lastMonth = ReviewHeader::where('created_at', 'like', Carbon::now()->subMonth(1)->format("Y-m")."%")->count();
You can use whereBetween as well.
$firstDayofPreviousMonth = Carbon::now()->startOfMonth()->subMonth()->toDateString();
$lastDayofPreviousMonth = Carbon::now()->subMonth()->endOfMonth()->toDateString();
$approved_reviews_lastMonth = ReviewHeader::whereBetween('created_at', [$firstDayofPreviousMonth,$lastDayofPreviousMonth])->count();

Can't get monthy CarbonPeriod to behave as desired

In the project I'm working on I have a daily command that basically checks the date of the last record in the database and tries to fetch data from an API from the day after and then each month after that (the data is published monthly).
Basically, the last record's date is 2019-08-30. I'm mocking as if I were running the task on 2019-09-01 with
$test = Carbon::create(2019,9,1,4);
Carbon::setTestNow($test);
I then create a monthly period between the next day of the last record's date and the last day of the current month like so:
$period = CarbonPeriod::create($last_record_date->addDay(), '1 month', $last_day_of_current_month);
Successfully generating a period with start_date = 2019-08-31 and end_date = 2019-09-30. Which I use in a simple foreach.
What I expected to happen is that it runs twice, once for August and once for September, but it's running only once for the start date. It's probably adding a month and going past the end date, but I don't know how to force the behaviour I'm looking for.
TL;DR:
$period = CarbonPeriod::create('2019-08-31', '1 month', '2019-09-30');
foreach ($period as $dt) {
echo $dt->format("Y-m") . "<br>\n";
}
This will print just 2019-08, while I expect 2019-08 and 2019-09. What's the best way to achieve that?
Solution :-
You can store actual date in $actual_day and current date for occurring monthly in $current_day. Put a check on comparing both dates, if not matched then make it on the same day it will skip 30,31 case in case of February month.
$current_date = $current_date->addMonths(1);
if($current_date->day != $actual_day){
$date = Carbon::parse($date->year."-".$date->month."-".$actual_day);
}
Your start date is 2019-08-31. Adding a month takes you to 2019-09-31. 2019-09-31 doesn't exist so instead you get 2019-10-01, which is after your end date. To avoid this I'd suggest you use a more regular interval such as 30 days.
Otherwise you're going to have to rigorously define what you mean by "a month later". If the start date is 31st Jan is the next date 28th February? Is the month after 28th or 31st March? How do leap years affect things?

Laravel/PHP/Carbon parse a date to one and three days from now() to the hour, disregarding minutes and seconds

I'm using Laravel 5.4 and Carbon to find dates that are exactly one day and three days prior to a laravel job (to the hour) to send notifications. So for example if the date was 2019-03-10 18:00:03 or 2019-03-10 18:15:34, I'd like to send a notification tomorrow at 2019-03-07 18:00:00 and another at 2019-03-09 18:00:00. I'd like to do this in an eloquent query, but not really sure how to "lazy match" by day and hour. If I have an Appointment model with a start_date timestamp, I know I can do exact matches by day or date, but I want to find matches that disregard the hours/seconds. I was considering something along these lines:
$oneDayAppointments = Appointment::whereDay(
'start_date',
Carbon::now()->addDay()->day
)->get();
...would get me any appointments where the start_date is a day from now. Now how would I hone it to the day and hour. If I were to just use a where clause:
$oneDayAppointments = Appointment::where(
'start_date',
Carbon::now()->addHours(24)
)->get();
...I could get exact matches, but only if the minutes/seconds were a match as well. Thanks!
Working on my comment above, this should do it
$tomorrowStart = Carbon::createFromFormat('Y-m-d H:i:s', Carbon::now()->addDay()->format('Y-m-d H:00:00'));
$tomorrowEnd = $tomorrowStart->copy()->addHour()->subSecond();
//whereBetween('start_date', [$tomorrowStart, $tomorrowEnd])
https://laravel.com/docs/5.8/queries

Laravel, Carbon. Get count of hours for a specific month between dates

How to get the number of hours referring only to the one month between 2 dates?
For example, how to get count of hours for December for first or for second row at the screenshot?
I tried this (subMonths generated in the loop, so no worry about it):
$bookings = Booking::whereDate('departure_date', '>=', Carbon::now()->subMonths($i)->startOfMonth())
->orWhereDate('arrival_date', '<=', Carbon::now()->subMonths($i)->endOfMonth())->get();
and then:
foreach ($bookings as $book) {
echo Carbon::parse($book->departure_date.$book->departure_time)->diffInHours(Carbon::parse($book->arrival_date.$book->arrival_time));
}
But in this case I get count of hours for whole booking, how to get it only for December?
p.s. I need this for calculating the statistics (booking percentage).
You would likely need to ->addMonth() then go to the ->startOfMonth() then use diffInHours().
Carbon::parse($book->departure_date)
->addMonth()
->startOfMonth()
->diffInHours(Carbon::parse($book->arrival_date.$book->arrival_time));
I've omitted $book->departure_time otherwise the timestamp wouldn't be the first second of the first day of the month.

Resources