Laravel 5.2 eloquent compare date time to current data and time - php

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

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: Incorrectly displayed date of messages from database

Now I send a message to my inbox app. You can see saved a message in image:
Message send in 16:55. But in my local site date of message incorrectly displayed:
Why is the date sent message not displayed correctly? Laravel app config timezone set "Asia/Tashkent"
Code:
$today = Inbox::where($message, $user_id)->whereDate('created_at', Carbon::today())->latest()->paginate($perPage);
$thisYear = Inbox::where($message, $user_id)->whereBetween('created_at', [now()->startOfYear(), Carbon::yesterday()->endOfDay()])->latest()->paginate($perPage);
$pastYear = Inbox::where($message, $user_id)->where('created_at', '<', now()->startOfYear())->latest()->paginate($perPage);
As said in the comments, you're formatting this date with created_at->format('H:m').
In PHP, m refers to the month, not the minute, which is i. It's printing 01 because that's the date's month.
Use this instead:
created_at->format('H:i')
Please try that way :
$today = Inbox::where($message, $user_id)->whereDate('created_at',DB::raw('CURDATE()'))->latest()->paginate($perPage);
Let’s say you want to filter out entries created today. You have a timestamp field created_at, right? How do you filter the DATE only from that timestamp? Apparently, Taylor thought about it.
I’ve seen people doing it with raw queries, like this:
$q->where(DB::raw("DATE(created_at) = '".date('Y-m-d')."'"));
Or without raw queries by datetime, like this:
$q->where('created_at', '>=', date('Y-m-d').' 00:00:00'));
Luckily, Laravel Query Builder offers a more Eloquent solution:
$q->whereDate('created_at', '=', date('Y-m-d'));
Or, of course, instead of PHP date() you can use Carbon:
$q->whereDate('created_at', '=', Carbon::today()->toDateString());

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

Get data filtering by local timezone from UTC

We have an application in Laravel 5.2. In our database, published_at stores date in timestamp with carbon instance in UTC, just as created_at and updated_at.
Every post is supposed to be published at midnight in every timezone. We saved our dates data in UTC format, like
'published_at' => '2016-04-12 00:00:00'
What we want to do is like;
if a person in US views it, then he/she sees that post after his/her midnight time. If a person in China views it, then he/she sees that post after his/her midnight time. How can we achieve this?
This is what we are doing at the moment. But, we think it's not gonna work.
public function all($limit, array $data = [])
{
$posts = $this->post->with('categories')
->where(
'published_at', Carbon::now()->setTimezone($data['user_timezone'])
->format('Y-m-d 00:00:00')
)
->orderBy('published_at', 'ASC')
->paginate($limit);
}
This is the first time we are working in timezones and we have no idea. Any help would be greatly appreciated. Thank you.
It sounds like you're trying to do a "sequential timezone publish", where over the course of 24 hours, it's midnight somewhere.
Assuming you've grabbed the timezone from input somewhere (in $data?), you can use the standard Eloquent / Laravel Query Builder verbiage to construct the query you require:
https://laravel.com/api/master/Illuminate/Database/Query/Builder.html
public function all($limit, array $data = [])
{
$posts = $this->post->with('categories')
->where(
'published_at',
'<',
Carbon::now($data['user_timezone'])
->format('Y-m-d H:i:s')
)
->orderBy('published_at', 'ASC')
->paginate($limit);
}
That way as soon as "midnight" has occurred in the timezone being passed through, the "published_at" will have a value of "less than" the current timestamp, including it in the results.

Comparing dates with Query Builder

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

Categories