Get database search results between two date time period - mysql

In my database, there is a table called vehicle_schedule, and all the vehicle schedules are stored there. In that table, there is two columns name as date_from date_to.Both columns type is datetime.When I pass date like 2019-03-20 09:00:00 2019-03-25 12:00:00 I need to get all the vehicle schedules between that two DateTime range.
So far I have tried this,
$vehicleSchedule=DB::table('vehicle_schedule')
->select('vehicle_schedule.*')
->whereRaw("date_from >=? AND date_to <=?",array($date_from,$date_to))
->get();
return response()->json(["vehicleSchedule"=>$vehicleSchedule,"message"=>"Vehicle Schedule got successfully"]);
I expect all the vehicle schedules are in that given range. But it only got vehicle schedules between date values only. When I check with the time constraint it does not working properly.

You can use Laravel whereBetween for this:
$vehicleSchedule=DB::table('vehicle_schedule')
->select('vehicle_schedule.*')
->whereBetween('date_from', [$startDate, $endDate])
->whereBetween('date_to', [$startDate, $endDate])
->get();
This will only select records where the date_from and date_to are between the two dates.
Related SO post.
Documentation.

I highly recommend to use PHP Carbon to work with any datetime or timestamp field.
To convert the datetime field to Carbon use this in model.
protected $dates = ['date_from','date_to'];
Then, convert the input time to Carbon inside controller
$date_from = Carbon::parse('2019-03-20 09:00:00');
$date_to = Carbon::parse('2019-03-25 12:00:00');
In this way the query will more shorter, cleaner and efficient.
$vehicleSchedule = DB::table('vehicle_schedule')
->where('date_from','>=',$date_from)
->where('date_to','<=',$date_to)
->get();

Try this.
$start_date = date('Y-m-d H:i:s',strtotime('2019-03-20 09:00:00'));
$end_date = date('Y-m-d H:i:s',strtotime('2019-03-25 12:00:00'));
$vehicleSchedule=DB::table('vehicle_schedule')
->select('vehicle_schedule.*')
->where([['date_from','<=',$start_date],['date_to','>=',$end_date]])->orwhereBetween('date_from',array($start_date,$end_date))->orWhereBetween('date_to',array($start_date,$end_date))
->get();

Related

Get all records where age is less than from a date difference in laravel

I'm trying to get all the records of children for which age is less than 5 years.
The date to calculate age should be a future date e.g 2021-08-12
$date and $age are custom.
$date can be any future date and $age is a number (e.g 5)
I have written the following but it is not working.
$children=Child::whereRaw('DATEDIFF('.$date.', date_of_birth) < '.$age.'')
->get();
Here date_of_birth is a column in DB.
To Avoid Raw Expressions and complex query You can use Virtual Columns
1.Add this to your Migration after created_at column or you can create new Migartion
$table->char('date_of_birth_year',3)->virtualAs('DATE_FORMAT(FROM_DAYS(DATEDIFF(CURRENT_DATE, date_of_birth)),"%y")');
Run your Migrations
Now You can Run the following query to get the records that is created at specific month
$yearsOld = ['01', '02', '03', '04'];
$childrens = Child::query()
->whereIn('date_of_birth_year', $yearsOld)
->get();
If you want to Know more check the Below links
https://laravel.com/docs/8.x/migrations#column-modifiers
https://www.w3schools.com/sql/func_mysql_date_format.asp
You can use whereBetween method. And compare it to now() or any other datetime
Child::whereBetween('date_of_birth', [now()->subYears(5), now()])->get();
Finally after debugging i found a solution. The problem was that the $date was not passed as string due to which there were no days found and I had to convert the days into years. This may help to someone.
$children=Child::whereRaw('(DATEDIFF("'.$date.'",date_of_birth)/365) < '.$age.'')
->get();

How to query a date using strftime to format

I am trying to grab all the records for the month. The string I have to query with is in this format 2019-01-12. The record I am querying for is a DateTime record so it has a format like this 2018-08-11 13:39:22.959330.
So I am trying to structure a query that would achieve this
Score.where('user_id = ? AND date_closed.strftime("%Y-%m) = ?', current_user.id, date)
Where date is the 2019-01-12 string. The above code produces the error
FUNCTION date_closed.strftime does not exist
I did google but was unable to locate something that achieved this. Most solutions involved searching inside a range of dates, I would really like to try to keep the search method the same.
You have the DATE_FORMAT function for that https://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_date-format
DATE_FORMAT(date_closed, "%Y-%m")
EDIT: you'll have to also format the date you are passing to the query
You can use mysql data functionos YEAR and MONTH:
Score.where('user_id = ? AND YEAR(date_closed) = ? AND MONTH(date_closed) = ?', current_user.id, date.year, date.month)

How to get data type date from database?

I have table Birthdays.
Birthdays fields: id | user_id | birthday (type date: y-m-d)
Data from url $_GET['date'] is '1991-09-10'
In BirthdaysController i have a query
$arrayDate = $this->Birthday->find()->where(['birthday' => $_GET['date'] ])->all();
but i want to find by format '1991-09'.
Any help would be greatly appreciated.
Please help me!
I guess what you want to do is to find people with a birthday date for the month of the year given?
First of all, you should use the GET parameters like this $this->request->query('date'); and not like this $_GET['date'].
You'll have to use the between function, so to be sure you're using the first and last day of the month, convert the date like this :
$startDate = $endDate = new \DateTime($this->request->query('date'));
$startDate->modify('first day of this month');
$endDate->modify('last day of this month');
And then you just have to create a query like this
$arrayDate = $this->Birthday
->find()
->where(function($exp) {
return $exp->between('birthday', $startDate->format('Y-m-d'), $endDate->format('Y-m-d'), 'date');
});
They're other ways to use this between find conditions, you should read this.

Calculate Avg Sum of days from column with type DATE in yii2 with diiference from today date

I need help with query or way to do with single query in yii2.
Application is in yii2 , working on admin dashboard. I need to show the Avg days of all products in stock from today date that has been in system which are enabled (in short average age of inventory that is in stock).
NOTE : Just a single avg total required for column to show count on dashboard as a result.
I have a table with column stock_date , that stores in DateTime format Y-m-d H:i:s.
Formula
( STOCK_DATE - TODAY DATE ) will give you age of single product in system.
Total SUM of column `stock_date' / Total number of products that are enabled
will give you average days.
Table columns:
inventory_id (primary key)
status (1 for enabled)
stock_date (datetime)
stock_date column screenshot
$AvgStatsCount = Inventory::find()
->select('sum(stock_date ) as stockdate')
....
->all();
Anyone know how to do that in right way ?
Posting Answer : working code for me :
$query = new Query;
$query->from('mytable')->where(['status' => 1]);
$AvgStatsCount = $query->average('DATEDIFF(stock_date, CURRENT_DATE())');
For this i recommend to use yii\db\Query instead of your model class that extends from ActiveRecord. With Query you can use methods like average, min and max that take a column name or SQL expression string as param and return the max, min or average value from the query.
To get the difference of stock_date - today i don't understand what format you are using, so i can't help you like this with that.
Edit:
So with stock_date in Y-m-d H:i:s date format, you can do something like this with yii\db\Query class:
use yii\db\Query;
...
$query = new Query;
$query->from('myTable');
$query->where(['>', 'stock_date', date('Y-m-d')]);
$average = $query->average('DATEDIFF(`stock_date`, CURRENT_DATE())');

Date value of datetime column using FLUENT in laravel 5.0

How could i get only de date of a datetime column in laravel 5 using fluent?
I want to compare this 2015-08-30 23:00:00 with this:
$dt = Carbon::now();
$d = $dt->toDateString();//this is the date only which i want to compare
There is a mysql function called DATE which extract the date part of a date or datetime expression like this DATE(`datetime`) but if i use it it gives me a integrity error.
Here's how i tried to use it:
$reservations = \DB::table('reservations')
->select('reservations.id','DATE(reservations.datetime)')
->get();
Follow the code to get the all of record in the date '2016-07-14' by using it
whereDate('date','=','2016-07-14')
if your date is available in a variable $date then use the below code
whereDate('date',$date)
Nobody answered so i'll post how i solved it temporary:
Laravel provides something called Raw Expressions, so i what i did was use a raw select to get the date string of a datetime like this:
$reservations = \DB::table('reservations')
->select(\DB::raw('reservations.id, DATE(reservations.datetime)')
->get();
My goal was to compare a date from a datetime column with a Carbon date and here's how i did it:
$dt = Carbon::now();
$d = $dt->toDateString();//Only date from datetime
$reservations = \DB::table('reservations')
->whereRaw("DATE(reservations.datetime) = '".$d."'")
->select(\DB::raw('reservations.id, DATE(reservations.datetime)')
->get();
I used whereRaw to make a Raw sentence for the where clause.
If someone has a better way of do this same thing, maybe using Eloquent i would like to know it since Eloquent is a bit more secure...
The correct way to do it and what you are looking for is this:
$query->whereDate('created_at', '=', date('Y-m-d'));
See here for more details for whereDate():
http://laravel.com/api/5.0/Illuminate/Database/Query/Builder.html#method_whereDate
http://laraveldaily.com/eloquent-date-filtering-wheredate-and-other-methods/
You can use whereDate for compare only date. flow bellow code.
whereDate('date', '=', $date)
If you give whereDate then compare only date from datetime field.