Laravel where dates by specific format - php

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

Related

Laravel 7 change date format to timestamp

Hello so right now I have this data that i retrieved from the database table and the format is ["2021-08-17 23:13:15"] and i wish to change it into something like this 1629243333 (another data) because i want to get the difference in days between both time. I tried using the gettimeStamp() but it doesnt work.
$updateRaw = \DB::table('tickets')
->where('id', $ticket)
->pluck('updated_at');
the $updateRaw is the data with the date format. Any help would be appreciated thanks
With Carbon do like this, if update_at column is not carbon instance;
use Carbon\Carbon;
Carbon::parse($updateRaw[0])->timestamp;
if it is then simply do
$updateRaw[0]->timestamp;
for more : https://carbon.nesbot.com/
A simpler solution would be to use native strtotime() to convert datetime to unix timestamp
$updateRaw = \DB::table('tickets')
->where('id', $ticket)
->value('updated_at'); //use value to get first value directly
$timestamp = strtotime($updateRaw);

Laravel - format date from Mysql database with carbon

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 :-

Laravel eloquent where date is equal or greater than DateTime

I'm trying to fetch relational data from a model where the date column is higher or equal to the current time.
The date column is formated as this: Y-m-d H:i:s
What I'm trying to do is to grab all rows where the Y-m-d H:i:s is in the future.
Example: lets assume the date is 2017-06-01 and the time is 09:00:00
Then i would like got all rows where the date is in the future, and the time is in the future.
Currently my code looks like this, and it's almost working but it doesn't grab the rows where the date is the current day.
public function customerCardFollowups() {
return $this -> hasMany('App\CustomerCardFollowup', 'user_id') -> whereDate('date', '>', Carbon::now('Europe/Stockholm')) -> orderBy('date', 'asc') -> take(20);
}
What am I doing wrong?
Sounds like you need to use >=, for example:
->whereDate('date', '>=', Carbon::now('Europe/Stockholm'))
Here you can use this:
->where('date', '>=', date('Y-m-d'))
Using whereDate will compare the date only and ignore the time. So your solution will give the records that are at least dating one day later and the records that are in the same day but with later hours will not be included.
If you use >= as suggested in other answers, you will get records starting from the current date and those ones who are even before the determined hour.
One solution for this is comparing using MySQL functions in whereRaw. In your code the condition for the date will be like this:
-> whereRaw("date > STR_TO_DATE(?, '%Y-%m-%d %H:%i:%s')" , Carbon::now('Europe/Stockholm')->format('Y-m-d H:i'));
In the code, I changed the format of Carbon date to match a specific format where you can use whatever format you want and put the same format in the STR_TO_DATE function.
For Laravel's TestCases:
$this->assertDatabaseHas('my_table', [
'name' => $name,
[ 'updated_at', '>=', $updatedAt ] // $updatedAt is a Carbon object
]);

Laravel format datetime

I have in my database the date of birth of a user, but I want to format that to something like 27 March 2000. I already have the date of registered and I can format that, but if I try to format the date of birth it gives me the following error:
Call to a member function format() on string
This code I used to show and format the date of birth of a user:
{{ucfirst(Auth::user()->created_at->format("M d Y"))}}
I tried to use this code for the date of birth because it is in a table with all the users:
{{ucfirst($user->birthdate->format("M d Y"))}}
This is the database structure:
http://i.stack.imgur.com/Agchg.png
You need to tell Laravel that your birthdate field is a date, otherwise Laravel will just fetch it as-is and not touch it at all. You do that by adding a protected $dates to the model-class which is an array of all fields which Laravel should treat as dates.
class MyModel extends [...] {
protected $dates = ['bithdate'];
}
This will tell Laravel that birthdate is a date and Laravel will convert it to a instance of Carbon.

Laravel4 - handling date format between whole application and mysql

In laravel 4 i have lots of database fields that having date type and datetime . but i am need to show date format like dd/mm/yy H:i:s like any format and also have to handle date formation on insertion and update. Is they any way to get works in one place?
Yes you can do that, by creating mutator method in your model; for example, if you have a Post model and has a date_of_birth property and you want to set the date in yyyy/mm/dd H:i:s but user is probably providing the date in a different format. In this case crate a mutator method in the Post model like this:
public function setDateOfBirthAttribute($value)
{
// value will be the given date by user
$dt = \Carbon\Carbon::createFromFormat('Y/m/d H:i:s',$value)->toDateString();
$this->attributes['date_of_birth'] = $dt;
}
To access the date just create an accssor method like:
public function getDateOfBirthAttribute()
{
return \Carbon\Carbon::createFromFormat('d-m-Y H:i:s', $this->date_of_birth);
}
Now the date_of_birth will be inserted using the format that you have used in the mutator method and when you'll show that date, it'll be displayed using the format that you have used in the accessor method. You may also check the Date Mutators.
A must have package for dates is Carbon. Take a look at the documentation on GitHub: https://github.com/briannesbitt/Carbon

Categories