Comparing dates with Query Builder - php

I am trying to add a parameter addWhere in my Query Builder that will make it retrieve a date similar to today's date (matching the month and day). My dates stored in Database looks like 1895-04-14 00:00:00, so if today is 14-04 regardless the year it will give me this record. Here's what I've got so far.
->select('r')
->where('r.status = :status')
->setParameter(':status', 1)
->andWhere('r.dateOfDeath = :now')
->setParameter('now',\date("m-d", time()))
->getQuery();
return $qb->getArrayResult();
How can I get all the entries from the database matching today's day and month?

since the querybuilder should accept native SQL-code:
->andWhere('r.dateOfDeath >= NOW()')
should work...
or
->setParameter('now', (new \DateTime()->format('Y-m-d H:i:s')))
if you are using php 5.4 or higher should also work

Related

MYSQL date range query strange behaviour

i'm working on codeigniter and mysql db. I have run in to a issue where i need to show recent data as per date.
i have table name tbl_tournament where i'm going to fetch tournament data whose tournament_end_date >= $todays_date
My Query
$today = date("d/m/Y");
$this->db->select('*');
$this->db->from('tbl_tournament');
$this->db->where('is_deleted', FALSE);
$this->db->where('tournament_end_date_time >=', $today);
$this->db->order_by('tournament_start_date_time');
$query = $this->db->get();
return $query->result_array();
the output of this query is empty array
array();
When i manually change tournament_end_date_time = 01/04/2018 in database and query $this->db->where('tournament_end_date_time >=', '01/04/2017'); i get results. But when i change date in query as $this->db->where('tournament_end_date_time >=', '31/12/2017'); i get empty array.
In Mysql database i have used varchar as the data type tournament_end_date_time
Thank in Advance.
You store datetimes as strings (with VARCHAR type), hence they're compared as strings - character by character. For obvious reasons, '3' character is greater than '1'. That's why with filter set...
WHERE tournament_end_date_time >= '31/12/2017'
... you'll only get the results where corresponding values start from '31/12' - in other words, of December, 31 (of 2017 - or any year after it).
To solve the problem, you can use STR_TO_DATE() MySQL function to convert the existing column value to an actual date. Note that the param will be treated as a date literal as it follows 'YYYY-MM-DD' format:
WHERE STR_TO_DATE(tournament_end_date_time, '%d/%m/%Y') >= '2017-12-31'
... or, in PHP syntax, following CodeIgniter conventions:
$this->db->where(array(
"STR_TO_DATE(tournament_end_date_time, '%d/%m/%Y') >=" => date("Y-m-d")
));
A better choice is doing a single-time update operation on this column to convert all its values to DATE type at once.

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
]);

Using Carbon in Eloquent Query

Good day everyone,
I'm currently realising a system that lets colleagues fill in their worked hours and what they worked on. I save those into the database using a time_stamp (date) named in the table. Now I have been trying to get the values of the filled in registrations of last week (I created some dummy times). And I have been trying to use Carbon and the Eloquent query builder at the same time, and i'm completely stuck. Would anyone mind to help me out?
$currentDate = \Carbon\Carbon::now('GMT+2');
$agoDate = $currentDate->subDays($currentDate->dayOfWeek)->subWeek();
$weekly = Hoursregistration::pluck('date')->agoDate($currentDate);
return $weekly;
Is the code that should pick up the dates from the db (which works). But when I try to put in the variables containing the carbon methods. It doesnt work and throw me a Method agoDate does not exist. (View: /var/www/clients/client0/web319/web/resources/views/hoursregistrations/index.blade.php) error.
I would love some help as this is crucial to my education (kind of in a tight spot rn.)
As you ask for: all Hoursregistration records from 1 week ago until now
// Current date + GMT(+2) as stated in your question
$currentDate = Carbon::now('GMT+2');
// Date exactly 1 week ago
$agoDate = $currentDate->subDays($currentDate->dayOfWeek)->subWeek();
// Records with date -between- two values
// $weekly = Hoursregistration::whereBetween('date', [$agoDate, Carbon::now('GMT+2')])->get();
// Or even simpler, all records where date is 'higher' than 1 week ago
$weekly = Hoursregistration::where('date', '>', $agoDate)->get();
// Getting the dates with the `pluck` method on the returned $weekly collection
$dates = $weekly->pluck('date');
return $weekly;

Laravel 5.2 eloquent compare date time to current data and time

I am trying to make a notification for the agents in my CRM.
I store the date and time they pick in my database and compare it to the current data and time.
I have tried this:
$notification = Main::select('id') -> whereRaw('Date(notification) = CurDate()') -> where('user_id', '=', $userid) -> get();
it works perfectly but compare only the current date with the saved date.
What I am looking for is to compare the current date and time with the stored date and time. If that time and date match or passed then do anything.
I don't want to use Carbon because I don't know how to use it.
You can try something like this instead:
$notification = Main::select('id')
->where("notification", "<=", date("Y-m-d H:i:s"))
->get();

Query to get rows with a UNIX Timestamp of today

In my DB I have UNIX Timestamps as due dates for jobs that need to run. On a given day or a given hour I'd like to know which jobs need to run. I have the following code to query my jobs table:
$job = Model_Job::find('first',
array(
'where' => array(
array('status_id', 1), // active
array('due_date', today)
)))
The last array is just pseudo code of course. I came up with the following code to figure out if a timestamp is today.
date('Ymd', strtotime(Date::forge(time())->get_timestamp())) == date('Ymd', strtotime($job->due_date))
How would I combine that with my query? Is there a better way then looping through the queried array?
Now, this is probably not a good way but it was the first that came to mind.
$today = strtotime('today 00:00');
You can use the date from that snippet and set a WHERE due_date > $today I'm not quite sure how to do that with your database model.
edit: This relies on that you have correct timezone settings in your php configuration.
As sebastian pointed out, this will get all future dates also, but you could simply use the same technique to get the last timestamp of the day
$todaystart = strtotime('today 00:00'));
$todayend = strtotime('today 23:59:59'));
and the use a BETWEEN operator in your SQL-query

Categories