I'm trying to use 'whereBetween' eloqouent query with two given start and end dates.
$first_day_this_month = date('Y-m-01 H:s:i'); //get the first day of the current month
$yesterDay = date('Y-m-d H:s:i',strtotime("-1 days")); //get yesterday's date
$d = m_chat_history::where('employee_id',$request->other_id)
->whereNull('to_group')->where('to_employee_id',$request->id)
->whereBetween('created_at',[$yesterDay,$first_day_this_month])
->get();
I make sure I have all the required data for the query by 'var_dump' and it did gives me all the required data needed for the query but the query returns me an empty output. Any ideas, clues, suggestions, help, recommendations please? I tried to remove the 'whereBetween' and my query works like it returns me the expected output but with 'whereBetween', the return output is empty.
Make sure to use the same type and format as created_at when defining the values for whereBetween. As you're using datetime you could define edge values like (just one of many ways of doing it):
$first_day_this_month = date('Y-m-01 H:i:s');
$yesterday = date('Y-m-d H:i:s', strtotime("-1 day"));
Also make sure of the order of params (still please consider edge cases like first day of the month where $yesterday would be smaller, so you have to add some logic and be careful):
->whereBetween('created_at', [$first_day_this_month, $yesterday])
Edit: wasn't timestamp...
Try this,
but first you have to install Carbon with composer.
after doing that
use Carbon
then write the fallowing code
$yesterday = Carbon::yesterday()->toDateTimeString();
$carbon = new Carbon('first day of ' . date('F Y'));
$first_day = $carbon->toDateTimeString();
and in your query
->whereBetween('created_at', [$first_day, $yesterday])
Related
I am new to laravel, I am building a small application which alerts when event date is a week away from current date. Here is my controller code
public function index()
{
$domain_count = domain_details::get()->count();
$domain_alert = domain_details::
where('domain_ex_date','>',date('Y-m-d'))
->get();
}
The domain_ex_date is in the format (YYYY-mm-dd) stored with the help of Carbon. The line where('domain_ex_date','>',date('Y-m-d')) gets me whole record when the domain_ex_date is away from the current date. i.e 2017-06-12 > 2016-09-15 gets the whole record. Here what i want to do is , i want to filter and get the only records which is only a week away from the current date. How do i do this ? i have tried like subweek() and subdays() but nothing helped.
I should get the record only when it satisfies this condition domain_ex_date - current date = 7
You can use strtotime():
domain_details:: where('domain_ex_date','<',date('Y-m-d',strtotime("+7 days")))
-> where('domain_ex_date','>',date('Y-m-d'))
->get();
Use Carbon!
Carbon is a build in date-extension ... Try it! :)
$week = Carbon::now()->addWeek();
$now = Carbon::now();
domain_details::where("domain_ex_date","<" $week)
->where("domain_ex_date", ">" $now)
->get()
Or you could also use the addDays($days) method!
$week = Carbon::now()->addDays(7);
I used carbon and this is what worked well for me
$week = Carbon::now()->subWeek();
$now = Carbon::now();
$domain_count = domain_details::get()->count();
$domain_alert = domain_details::where("domain_ex_date",">", $week)
->where("domain_ex_date", "<" ,$now)
->get();
I'm writing a scope query and I'm passing in a fetch_date to pull things from the DB table based on the created_at timestamp.
I'm trying to find all records for a month, but the variable $fetch_date keeps changing whenever I try the following:
//$fetch_date is a carbon instance and is equal to the month the user selected
//ie: Carbon {#221 ▼
// +"date": "2016-07-01 00:00:00.000000"
//Create the next_month
$next_month = $fetch_date->addMonth();
//Format next_month as a string
$next_month = $next_month->format('Y-m-d');
//Format fetch_date as a string
$fetch_date = $fetch_date->format('Y-m-d');
dd($fetch_date);
//This now gives me 2016-08-01 - why?
Why does the fetch_date change? I'm essentially trying to keep the $fetch_date as the current month and the $next_month to simply be the start of the next month.
I'm guessing there's a real simple reason to this I'm just overlooking.
Because calling the addMonth method has side effects.
If you look at Carbon's source, you'll see that all addMonth is doing is calling addMonths with a value of 1, which in turn is simply calling DateTime::modify. It's not explicitly spelled out in the documentation, but from the examples it's pretty plain that calling the method modifies the stored time value:
Example #1 DateTime::modify() example
<?php
$date = new DateTime('2006-12-12');
$date->modify('+1 day');
echo $date->format('Y-m-d');
?>
To avoid this, keep a copy of of the time around and modify that:
$also_fetch_date = clone $fetch_date;
$next_month = $also_fetch_date->addMonth();
// ...
Seems you are adding a month to the fetch_date variable.
Try this:
$next_month = Carbon::createFromFormat('Y-m-d', $fetch_date->format('Y-m-d'));
$next_month->addMonth();
dd($next_month->format('Y-m-d'));
Take a look at the documentation of Carbon: http://carbon.nesbot.com/docs/
Maybe will help you
I am building a query to get all servicios of specific motoboy but I need that they are of the current day. The data type of that attribute is timestamp. I have this code but doenst work
Motoboy::with(array('servicios' => function($query){
$query->where('id_estado', '1')->orWhere('id_estado', '2')
->where('fecha_hora', new DateTime('today'));
}))->where('auth_token',$auth)->firstOrFail();
new DateTime is instantiating an object and does not have the the format you need for timestamp.
A simple solution is to use the date() function to specify the format you want, so for the current timestamp you would use date('Y-m-d H:i:s')
Also, I would recommend that you query the entire day like this:
$startToday = date('Y-m-d 00:00:00');
$endToday = date('Y-m-d 23:59:59');
// ...
->whereBetween('fecha_hora', array($startToday,$endToday));
// ....
Your code would turn into this:
Motoboy::with(array('servicios' => function($query){
$startToday = date('Y-m-d 00:00:00');
$endToday = date('Y-m-d 23:59:59');
$query->where('id_estado', '1')->orWhere('id_estado', '2')->whereBetween('fecha_hora', array($startToday,$endToday));
}))->where('auth_token',$auth)->firstOrFail();
I have a web app written in Laravel 3. In this application one of the models is "Activities". These activities have both a start date and end date field. I was wondering what the best way is to query all Activities that start AND end the same day?
-- Update --
I'm using mySQL and the field types are both Timestamp...
What I have currently:
...
$activitySchedule = ActivitySchedule::with(array('location'))->where(function($query) {
// Query activities that start and end today
$yesterday = date('Y-m-d', strtotime('today')) . ' 00:00:00';
$tomorrow = date('Y-m-d', strtotime('today')) . ' 23:59:59';
$query->where('starts', '>', $yesterday);
$query->where('ends', '<', $tomorrow);
});
...
I think this works properly but I'm wondering if there is a more precise method?
You should be using Carbon package which would allow you to get startOftheDay and endoftheday like this:
$StartofDay = Carbon::now()->startOfDay();
$EndofDay = Carbon::now()->endOfDay();
Once you have this in place, query your model with a where condition involving a condition to check using StartofDay and EndofDay values along with created_at column.
Find carbon package here : https://github.com/briannesbitt/Carbon
Hope it helps.!!
I have a date returned from an sql query (a datetime type field) and want to compare it to today's date in PHP. I have consulted php manual and there are many ways to do it. I finally came up with a solution comparing strings, but I would like to know if there are either any 'better' (best practice), cleaner or faster ways to do it. This is my solution:
// $sql_returned_date='2008-10-17 11:20:04'
$today = new DateTime("now");
$f_today=$today->format('Y-m-d'); //formated today = '2011-03-09'
$sql_date=substr($sql_returned_date,0,9); //I get substring '2008-10-17'
if($f_today==$sql_date)
{
echo "yes,it's today";
}else{
echo "no, it's not";
}
thanks
Seriously guys?
//$mysql_date_string= '2013-09-20' OR '2013-09-20 12:30:23', for example
$my_date = new DateTime($mysql_date_string);
if($my_date->format('Y-m-d') == date('Y-m-d')) {
//it's today, let's make ginger snaps
}
You could factor this into the data returned from your database query:
SELECT `DateOnDB`,
DATE(`DateOnDB`) = DATE(CURDATE()) AS isToday
FROM `dbTable`
and simply use PHP to test the value of the isToday column
Excuse me for being a question-digger, but I was trying to achieve the same thing, and I found a simple solution - if you want to select only rows with today's date you can do :
WHERE DATE(datetime_column)=CURDATE()
in your mySQL query syntax.
You'd have three solutions :
Working with strings, like you are doing ; which seems like a solution that works ; even if it doesn't feel clean.
Working with timestamps, using strtotime() and time() ; which is a bad idea : UNIX Timestamps only work for dates that are greater than 1970 and lower than 2038
Working with DateTime everywhere ; which would both work and feel clean.
If I need to make any calculation on the PHP-side, I would probably go with the third solution -- but the first one would be OK in most cases, I suppose.
As a sidenote : instead of formating your date to Y-m-d, you could check if it's :
Greater of equal than today
Less than tomorrow.
If SQL returned date is in this format 2011-03-09 (date format without timing),
$sqlret = "2011-03-05";
$curdate = date('Y-m-d');
echo $diff = strtotime($curdate) - strtotime($sqlret);
echo $no_diff = $diff/(60*60*24);
If the date with time like:
$sqlret = "2011-03-05 12:05:05",
Just make your current date format also like that:
$curdate = date('Y-m-d H:i:s');
If it doesn't satisfies your need, ask your question with some example.
You can use new DateTime php Object that way.
$date1 = new DateTime('2012-01-21');
$date2 = new DateTime ( 'now');
$interval = $date1->diff($date2);
if( $interval->format('%R%a ') == 0){
echo 'it s today';
}
I'd do that:
# SQL
SELECT DATE_FORMAT(date_col, "%Y-%m-%d") AS created_at FROM table
# PHP
if ( date('Y-m-d') == $sql_date ) { // assuming $sql_date is SQL's created_at
echo 'today';
}
$time = //your timestamp
$start = mktime(0,0,0,date("j"),date("n"),date("Y"));
$end = mktime(23,59,0,date("j"),date("n"),date("Y"));
if($time > $start && $time < $end){
//is today
}