Laravel - format date from Mysql database with carbon - php

In my Laravel project I have a MySQL database table with the following column:
| requested_at |
2018-02-03 12:00:00
2018-03-03 11:00:00
I want to get all items from this column where the timestamp (requested_at) is older than 60 days:
$now = Carbon::now ();
$60days = DB::table('exampletable')->where('requested_at', '=', $now->subDays(60))->get();
For my following code I need to format the Date format from my column requested at.
I only want to get the date like this 2018-03-03 without the time.
I play around with some carbon methods but It didn't work at all:
$format60 = Carbon::createFromFormat('Y-m-d', $60days);

It seems that you are using TIMESTAMP type so
->where('requested_at', '<=', now()->subDays(60)->startOfDay())->get();
As you can see there is no need to format Carbon instance.
Break it all down:
now() // Laravel helper to get Carbon::now()
->subDays(60) // subtract 60 days
->startOfDay() // set time part of timestamp to start of the day
Note: add requested_at into $dates array in your model for easier use

You can achieve this by mysql only, no need of carbon.
Just using datediff() and now() of mysql.
Do like this
$days60 = DB::table('exampletable')
->whereRaw('datediff(now(),requested_at) = 60')
->get();
Example :-

Related

Laravel where dates by specific format

In DB Col Name('publish') varchar format d/m/Y for Example 30/1/2020
when try to get dates less than 30/1/2020 get any date less than days
for example
->where('publish','<','30/01/2020')
29/2/2020 less than 30/1/2020 so i get any date under 30 by day not month or year
on your Eloquent model define an accessor to retrive publish as carbon object
public function getPublishAttribute($date)
{
return Carbon::parse($date)->format('d/m/Y');
}
now on your controller compare both date as below
->where('publish','<',Carbon::parse('30/01/2020'))
hope it helps!
You can use DB::raw and str_to_date for the same:
->where(DB::raw('str_to_date(publish, "%d/%m/%Y")'),'<','30/01/2020' )
str_to_date will convert your varchar field to datetime field.
MySQL -> Date and Time Functions-> STR_TO_DATE

Set end of day instead of 00:00:00 in laravel

When we pass a date value like this 2019-01-01 without the time 10:00:00, the time defaults to 00:00:00. So finally the db compatible value gets transformed into this: 2019-01-01 00:00:00. How can I force default it to 23:59:00 instead?
Example: I need to set an expiry_date attribute, but if I only take the date input 2019-01-08 from user, the user is going to assume that they will have the entire day as expiry date, when in reality it will expire at the very first second of 2019-01-08 because of the implicit default time 00:00:00.
How do I overcome this? How can I set a mutator for expiry_date that would turn this 2019-01-01 00:00:00 into this 2019-01-01 23:59:00?
Just use the following:
$expiryDate = Carbon::createFromFormat('Y-m-d', $date)->endOfDay()->toDateTimeString();
This will take the date (update date format if needed), switch to the end of the day and convert the resulting object into a date time string.
Or, use it as an attribute setter:
/**
* #param $value
*/
public function setExpiryDateAttribute($value)
{
$this->attributes['expiry_date'] = Carbon::createFromFormat('Y-m-d', $value)
->endOfDay()
->toDateTimeString();
}
You may use something like the strtotime() function to add something to the current timestamp. $expiry_date = date("Y-m-d H:i:s", strtotime('+5 hours')).
If you need variables in the function, you must use double quotes then like strtotime("+{$hours} hours"), however better you use strtotime(sprintf("+%d hours", $hours)) then.
I used an DateTime property method like below:
date_create($your_date)->modify('+1 day -1 microsecond'),
It works on Laravel because datetime is PHP native.
-> Source <-

Laravel - select rows from previous week on monday

I have a table mdl_forum_posts with a field created that's a BIGINT (database is not mine, so don't blame for the type of field). An example of value is 1504170577. The value is saved as a timestamp.
There will run a cron every Monday (first day of the week) that needs to select all the rows created in the previous week (created value in week before).
I'm trying to do this:
$currentDate = \Carbon\Carbon::now();
$agoDate = $currentDate->subDays($currentDate->dayOfWeek)->subWeek();
$postsNL = DB::table('mdl_forum_posts')->whereBetween('created', array($agoDate,$currentDate))->get();
But this isn't returning any rows (and it should!).
Keep in mind that when you do some operations on a Carbon object it will modify the instance of the object itself, so basically when you run the statement
$agoDate = $currentDate->subDays($currentDate->dayOfWeek)->subWeek();
you are also modifying $currentDate.
The below code should do the trick:
$currentDate = \Carbon\Carbon::now();
$agoDate = $currentDate->copy()->subDays($currentDate->dayOfWeek)->subWeek()->setTime(23, 59, 59);
$postsNL = DB::table('mdl_forum_posts')
->whereBetween('created', array($agoDate->timestamp, $currentDate->timestamp))
->get();
The copy method will make all the modifications on a copy of the Carbon instance, not affetting the original one.
Hope it helps
Why should it? MySQL won't just compare an integer to a date. The integers are called unix timestamps and you can easily get unix timestamps out of Carbon by using the timestamp property on a Carbon instance:
$postsNL = DB::table('mdl_forum_posts')
->whereBetween('created', array($agoDate->timestamp, $currentDate->timestamp))
->get();
Since Carbon extends DateTime, you could also use the getTimestamp method.

PHP Date Issue with Excel Sheet

I am trying to convert an old office excel sheet document data into PHP web based app for searching and other data analysis. Stuck in how to fields called start_date & end_date. This tells me that if project is active or not. Data saved in below format. It compares both dates and return the project status by comparing with current date.
Start_Date End Date Status
1-Jan-16 31-Dec-16 Active or not
I tried with PHP date("Y-m-d") function but month is an issue.
You can use the strtotime() function on your excel derived dates and then convert it to a usable DateTime value using date() like so:
$time_before = strtotime('1-Jan-16');
$date_before = date('Y-m-d', $time_before); // 2016-01-01
$time_after = strtotime('31-Dec-16');
$date_after = date('Y-m-d', $time_after); // 2016-12-31
Then compare the two dates against each other.

PHP Carbon & MySQL inserting 9999-31-12 into table ends up as 0000-00-00

I am using Carbon to manipulate my dates in my PHP7 / Laravel 5.2 / MySql 5.7 project.
I am trying to insert a date of 9999-12-31 23:59:59 into a timestamp field but it resolves to all zeros when inserted.
My migration creates the column like so:
$table->timestamp('end_date');
My code generates the date like this:
$endDate = Carbon::create(9999, 12, 31, 23, 59, 59);
I then insert it into the table like this:
ClientSubscription::create([
'end_date' => $endDate,
])->save();
I can see (via a screen dump during the migration) that the date is generated correctly as a Carbon instance, like this:
ED= : {
"date": "9999-12-31 23:59:59.000000",
"timezone_type": 3,
"timezone": "UTC"
}
Yet the result from a query of my table is:
0000-00-00 00:00:00
I am careful to not work off this date prior to insertion with Carbon, so I copy this date as soon as it is generated then use the copy to calculate periods, etc.
All other calculated dates (different to this date) insert OK into the field using the same create routine.
What have i missed? Thanks!
I am using the suggestion from #CD001 and set the date to null.
My migration now is:
$table->timestamp('end_date')->nullable();
Then instead of checking for 9999 date like this:
if($endDate->year == 9999) {
I check like this:
if(! $endDate) {
This works. Thanks #CD001!

Categories