Laravel 4 Eloquent - where timestamp is over 3 years old - php

I have a field called RegistrationDate which I need to check for time since.
I need a where claus that will do:
if (time() - strtotime($car->RegistrationDate) > 3*365.25*24*60*60)
over 3 years old
}
So:
$cars::where('RegistrationDate', '>', '3 years old')->get();
but don't know how to do that, my dates are saved as timestamps: 2009-07-17 00:00:00.
thanks.

Use the Carbon Library. I think it is loaded by the laravel framework already. But if not you can load via composer. https://github.com/briannesbitt/Carbon
$cars::where('RegistrationDate', '>', Carbon\Carbon::now()->subYears(3))->get(); Assuming $cars is an eloquent object for your Car model;
Also, unrelated to question... but your table naming conventions are a bit weird.
$cars = Car::where('registration_date', '>', Carbon\Carbon::now()->subYears(3))->get();

You can also use DateTime and DateTimeInterval class:
$currentDate = new DateTime(); // get current date time
$currentDate->sub(new DateInterval('P3Y')); // substract 3 years from current date
After that you can use $currentDate in your code like:
$cars::where('RegistrationDate', '>', $currentDate)->get();
You can also convert $currentDate to sql datetime string you needed with:
$currentDateStr = $currentDate->format('Y-m-d H:i:s');

Related

CARBON TIME FORMATS [duplicate]

This question already has an answer here:
Change Date format using Carbon
(1 answer)
Closed 1 year ago.
i am using Laravel 5.8 and in database there is a column name last_seen here stored values are in that format (2021-02-05 00:42:14) i want to customise this format on listing of a page just like this (22/04/2021 03:59:54)
how can i do that ??
You can try using Carbon DateTime
Carbon::parse($user->last_visit)->format('d/m/Y H:i:s');
Include last_seen in the dates array in your model. Then you can use Carbon to format it however you like.
//in your model
protected $dates = ['last_seen'];
//controller or view
$model->last_seen->format('d/m/Y H:i:s');
To address empty/null values in last_seen
optional($model->last_seen)->format('d/m/Y H:i:s');
Use this code for changing the format of DateTime:
$datetime = "2021-02-05 00:42:14";
$datetime_format = Carbon::parse($datetime)->format('Y/m/d H:i:s'));
Output:
"2021/02/05 12:42:14"
Explanation of the formating:
H - 24 Hour with trailing zeros
i - Minutes with trailing zeros
s - Seconds with trailing zeros
For more details about the formatting of date-time please follow the link below:
PHP Date

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)

How to compare dates in Carbon on Laravel Blade View? [duplicate]

This question already has answers here:
How to compare two Carbon Timestamps?
(4 answers)
Closed 5 years ago.
I wish to compare two dates - $dateX (datetime in past) with $currentDatetime (current datetime). For instance: check if $dateX was 7 days ago or not. All should happen in Laravel Blade Engine view by using Carbon.
Can you give some example? Thanks!
This think can be achieved easily with Carbon, so i'm supposing that both $dateX and $currentDateTime are Carbon instances, accordingly if you wanna check time diff in days simply use diffInDays
for example
if( $currentDateTime->diffInDays( $dateX ) > 7 ){
// do sonething here
}
in the end i really wanna say that carbon docs are very clear and easy to read
If you want to know if the date is earlier than a week ago, you could do this:
#if ($dateX < now()->subWeek())
The diffInDays() will work too, but only if all $dateX days are in the past and always will be. The code above is more explicit. Also, what if you'll need to change the logic?
First get these date times into carbon instances.
#if ($dateX->diffInDays($currentDateTime, false) == 7)
...
#endif
Carbon Docs - Difference
You can check this with diff. Also check if a date is set before the other.
$date1 = \Carbon\Carbon::create(2017, 10, 10);
$date2 = \Carbon\Carbon::create(2017, 10, 20);
$difference = $date1->diff($date2)->days;
$before = $date1 < $date2;
if (before && $difference < 7) {
//Date 1 more than 7 days before date 2
}

Laravel - select rows from previous week on monday

I have a table mdl_forum_posts with a field created that's a BIGINT (database is not mine, so don't blame for the type of field). An example of value is 1504170577. The value is saved as a timestamp.
There will run a cron every Monday (first day of the week) that needs to select all the rows created in the previous week (created value in week before).
I'm trying to do this:
$currentDate = \Carbon\Carbon::now();
$agoDate = $currentDate->subDays($currentDate->dayOfWeek)->subWeek();
$postsNL = DB::table('mdl_forum_posts')->whereBetween('created', array($agoDate,$currentDate))->get();
But this isn't returning any rows (and it should!).
Keep in mind that when you do some operations on a Carbon object it will modify the instance of the object itself, so basically when you run the statement
$agoDate = $currentDate->subDays($currentDate->dayOfWeek)->subWeek();
you are also modifying $currentDate.
The below code should do the trick:
$currentDate = \Carbon\Carbon::now();
$agoDate = $currentDate->copy()->subDays($currentDate->dayOfWeek)->subWeek()->setTime(23, 59, 59);
$postsNL = DB::table('mdl_forum_posts')
->whereBetween('created', array($agoDate->timestamp, $currentDate->timestamp))
->get();
The copy method will make all the modifications on a copy of the Carbon instance, not affetting the original one.
Hope it helps
Why should it? MySQL won't just compare an integer to a date. The integers are called unix timestamps and you can easily get unix timestamps out of Carbon by using the timestamp property on a Carbon instance:
$postsNL = DB::table('mdl_forum_posts')
->whereBetween('created', array($agoDate->timestamp, $currentDate->timestamp))
->get();
Since Carbon extends DateTime, you could also use the getTimestamp method.

change the date format in laravel view page [duplicate]

This question already has answers here:
Convert one date format into another in PHP
(17 answers)
Closed 12 months ago.
I want to change the date format which is fetched from database.
now I got 2016-10-01{{$user->from_date}} .I want to change the format 'd-m-y' in laravel 5.3
{{ $user->from_date->format('d/m/Y')}}
Try this:
date('d-m-Y', strtotime($user->from_date));
It will convert date into d-m-Y or whatever format you have given.
Note: This solution is a general solution that works for php and any of its frameworks. For a Laravel specific method, try the solution provided by Hamelraj.
In Laravel use Carbon its good
{{ \Carbon\Carbon::parse($user->from_date)->format('d/m/Y')}}
In your Model set:
protected $dates = ['name_field'];
after in your view :
{{ $user->from_date->format('d/m/Y') }}
works
You can check Date Mutators: https://laravel.com/docs/5.3/eloquent-mutators#date-mutators
You need set in your User model column from_date in $dates array and then you can change format in $dateFormat
The another option is also put this method to your User model:
public function getFromDateAttribute($value) {
return \Carbon\Carbon::parse($value)->format('d-m-Y');
}
and then in view if you run {{ $user->from_date }} you will be see format that you want.
There are 3 ways that you can do:
1) Using Laravel Model
$user = \App\User::find(1);
$newDateFormat = $user->created_at->format('d/m/Y');
dd($newDateFormat);
2) Using PHP strtotime
$user = \App\User::find(1);
$newDateFormat2 = date('d/m/Y', strtotime($user->created_at));
dd($newDateFormat2);
3) Using Carbon
$user = \App\User::find(1);
$newDateFormat3 = \Carbon\Carbon::parse($user->created_at)->format('d/m/Y');
dd($newDateFormat3);
Method One:
Using the strtotime() to time is the best format to change the date to the given format.
strtotime() - Parse about any English textual datetime description into a Unix timestamp
The function expects to be given a string containing an English date format and will try to parse that format into a Unix timestamp (the number of seconds since January 1 1970 00:00:00 UTC), relative to the timestamp given in now, or the current time if now is not supplied.
Example:
<?php
$timestamp = strtotime( "February 26, 2007" );
print date('Y-m-d', $timestamp );
?>
Output:
2007-02-26
Method Two:
date_format() - Return a new DateTime object, and then format the date:
<?php
$date=date_create("2013-03-15");
echo date_format($date,"Y/m/d H:i:s");
?>
Output:
2013/03/15 00:00:00
You can use Carbon::createFromTimestamp
BLADE
{{ \Carbon\Carbon::createFromTimestamp(strtotime($user->from_date))->format('d-m-Y')}}
I had a similar problem, I wanted to change the format, but I also wanted the flexibility of being able to change the format in the blade template engine too.
I, therefore, set my model up as the following:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
\Carbon\Carbon::setToStringFormat('d-m-Y');
class User extends Model
{
protected $dates = [
'from_date',
];
}
The setToStringFormat will set all the dates to use this format for this model.
The advantage of this for me is that I could have the format that I wanted without the mutator, because with the mutator, the attribute is returned as a string meaning that in the blade template I would have to write something like this if I wanted to change the format in the template:
{{ date('Y', strtotime($user->from_date)) }}
Which isn't very clean.
Instead, the attribute is still returned as a Carbon instance, however it is first returned in the desired format.
That means that in the template I could write the following, cleaner, code:
{{ $user->from_date->format('Y') }}
In addition to being able to reformat the Carbon instance, I can also call various Carbon methods on the attribute in the template.
There is probably an oversight to this approach; I'm going to wager it is not a good idea to specify the string format at the top of the model in case it affects other scripts. From what I have seen so far, that has not happened. It has only changed the default Carbon for that model only.
In this instance, it might be a good set the Carbon format back to what it was originally at the bottom of the model script. This is a bodged idea, but it would work for each model to have its own format.
Contrary, if you are having the same format for each model then in your AppServiceProvider instead. That would just keep the code neater and easier to maintain.
I suggest using isoFormat for better appearance on the web pages.
{{ \Carbon\Carbon::parse($blog->created_at)->isoFormat('MMM Do YYYY')}}
The result is
Jan 21st 2021
Carbon Extension
In Laravel 8 you can use the Date Casting: https://laravel.com/docs/8.x/eloquent-mutators#date-casting
In your Model just set:
protected $casts = [
'my_custom_datetime_field' => 'datetime'
];
And then in your blade template you can use the format() method:
{{ $my_custom_datetime_field->format('d. m. Y') }}
In Laravel you can add a function inside app/Helper/helper.php like
function formatDate($date = '', $format = 'Y-m-d'){
if($date == '' || $date == null)
return;
return date($format,strtotime($date));
}
And call this function on any controller like this
$start_date = formatDate($start_date,'Y-m-d');
Hope it helps!
For a more natural date format used everywhere outside of the US, with time that includes hours, minutes and seconds:
07/03/2022 19:00:00
{{ \Carbon\Carbon::parse($transaction->created_at)->format('d/m/Y H:i:s')}}
Or if you'd prefer to use a more natural 12-hour-clock-based time format like this:
07/03/2022 7:00:00 PM
{{ \Carbon\Carbon::parse($transaction->created_at)->format('d/m/Y g:i:s A')}}
Here's the full list of variables available for use in the PHP/Carbon date-time format.
Sometimes changing the date format doesn't work properly, especially in Laravel. So in that case, it's better to use:
$date1 = strtr($_REQUEST['date'], '/', '-');
echo date('Y-m-d', strtotime($date1));
Then you can avoid error like "1970-01-01"!

Categories