Laravel: Incorrectly displayed date of messages from database - php

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

Related

Laravel Eloquent Date Formatting

Having to make this post before I go insane, as none of the solutions I can find online are working.
My Laravel application isn't returning the right data because Laravel seems to be 'INSISTING' on using "m/d/Y" as the date format when running the query. My code is below...
$now = date("d/m/Y H:i:s");
$previousTime = (new DateTime($now))->modify('-1 minutes')->format('d/m/Y H:i:s');
$count = PlayLog::where('user_id', 1)->whereDate('created_at', '>=', $previousTime)->get()->count();
The data is stored in the database as d/m/Y, but Laravel is querying m/d/Y. How can I fix this?
UPDATE
I am official mad now, but the answer is whereDate() doesn't support time :/
You can take leverage of Carbon
Import use Carbon\Carbon;
Date formatting via carbon to match your DB
$previousDT = Carbon::now()->addDay(-2)->format('d/m/Y H:i:s'); // 10/05/2020 23:05:06
PlayLog::whereDate('created_at', '>=', $previousDT)

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 no results returned when working with datetime field

So I have this query:
Report::whereDate('date', '=', Carbon::now()->format('Y-m-d H:i'))->get();
Dates are stored like this for example:
2017-01-08 10:00:00
But I never get any results, does this have to do something with the seconds? If so, how can I avoid this and get my results? Using a mutator perhaps to ignore seconds?
PS. I want to get the results from the specified time, because I am using it for a scheduled task (command). E-mails should be sent at specified times, and the times vary :)
You can try with WhereRaw
$format = Carbon::now()->format('Y-m-d H:i');
Report::whereRaw("date_format(date, '%Y-%m-%d %H:%i ') = '$format'")
I figured it out, I didn't want to use a boolean in my database to check wether or not an e-mail has been sent for the specific report, because they are daily reports. But I will another cron job to reset these booleans at the end of the day.
Add date to $dates property in the Report model:
protected $dates = ['date'];
You said you want to check the time, so just do this:
Report::where('date', Carbon::now())->get();
I guess I've mis understood the question.
The convenient way to match date time is by using Carbon.
In your model add the following line.
protected dates = ['date'];
By doing that your dates will be saved as Carbon instance.
Now you can do
Report::whereDate('date', Carbon::now())->get();

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

Laravel Eloquent compare date from datetime field

I want to get all the rows from a table through an expression:
table.date <= 2014-07-10
But if the column contains a datetime let's say:
2014-07-10 12:00:00
But if I do:
where('date', '<=', $date)
it won't get the row.
I guess this is because $date = 2014-07-10 which makes MySQL assume that it is 2014-07-10 00:00:00.
In regular MySQL I would just do
where DATE(date) <= $date
What would be the equivalent using Laravel's Eloquent?
Laravel 4+ offers you these methods: whereDay(), whereMonth(), whereYear() (#3946) and whereDate() (#6879).
They do the SQL DATE() work for you, and manage the differences of SQLite.
Your result can be achieved as so:
->whereDate('date', '<=', '2014-07-10')
For more examples, see first message of #3946 and this Laravel Daily article.
Update: Though the above method is convenient, as noted by Arth it is inefficient on large datasets, because the DATE() SQL function has to be applied on each record, thus discarding the possible index.
Here are some ways to make the comparison (but please read notes below):
->where('date', '<=', '2014-07-10 23:59:59')
->where('date', '<', '2014-07-11')
// '2014-07-11'
$dayAfter = (new DateTime('2014-07-10'))->modify('+1 day')->format('Y-m-d');
->where('date', '<', $dayAfter)
Notes:
23:59:59 is okay (for now) because of the 1-second precision, but have a look at this article: 23:59:59 is not the end of the day. No, really!
Keep in mind the "zero date" case ("0000-00-00 00:00:00"). Though, these "zero dates" should be avoided, they are source of so many problems. Better make the field nullable if needed.
Have you considered using:
where('date', '<', '2014-08-11')
You should avoid using the DATE() function on indexed columns in MySQL, as this prevents the engine from using the index.
UPDATE
As there seems to be some disagreement about the importance of DATE() and indexes, I have created a fiddle that demonstrates the difference, see POSSIBLE KEYS.
You can get the all record of the date '2016-07-14' or before '2016-07-14' by choosing one syntax from follows:
->whereDate('date','=','2014-07-10')
->whereDate('date', '<=', '2014-07-10')
Or use the another code for dynamic date
whereDate('date',$date)
You can use this
whereDate('date', '=', $date)
If you give whereDate then compare only date from datetime field.
use Carbon\Carbon;
public function scopePublished($query)
{
$now = Carbon::now();
$date = Carbon::parse($now)->toDateString();
$time = Carbon::parse($now)->toTimeString();
return $query->whereDate('published_at', '<', $date)
->orWhere(function($query) use ($date, $time) {
$query->whereDate('published_at', '=', $date)
->whereTime('published_at', '<=', $time);
});
}
Here is my logic:
if you are comparing date then your method should be whereDate and if your comparing complete datetime then your method will be only where:
$calendar_alert = DB::table('calendar_alerts')->whereDate('when', '=', now()->format('Y-m-d'))->where('when', '>', now()->format('H:i:s'))->get();
If you're still wondering how to solve it.
I use
protected $dates = ['created_at', 'updated_at', 'aired'];
In my model and in my where i do
where('aired', '>=', time());
So just use the unix to compare in where.
In views on the other hand you have to use the date object.
Facing the same issue, I suggest to read this article : https://dev.to/nicolus/how-to-properly-retrieve-laravel-models-between-two-dates-1bek
Note that the statement :
The issue here is that our created_at column is usually a Datetime, so it's not a simple date but it also has a time. Which means that in practice any post created on the 30th won't be retrieved because their creation date will always be greater than 2021-06-30 (which SQL will assume means '2021-06-30 00:00:00').
... from the article isn't completly true because on my side I tested a direct comparison between a mysql "date" typed field and a string formatted like "2022-10-18", and the issue was the same, the "<=" didn't work right.

Categories