Laravel Eloquent Date Formatting - php

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)

Related

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

Date from API call not being accepted in Laravel as a dateTime field

I am getting dates from an API call. The date is formatted in this way
2017-10-19T15:30:00
I want to store this date in my MYSQL database using Laravel Database Migration, currently I am using
$table->dateTime('datetime');
When I store it using a dateTime field as above, all I get is
0000-00-00 00:00:00
When I use a timestamp format, I don't get accurate dates, I just get the current time and date.
How can I solve this? Any help would be appreciated, and please let me know if you want further information.
Luckily, Laravel uses the Carbon class, which makes things a lot easier to modify dates. In your case, you want to do this:
Carbon::createFromFormat('Y-m-d\TH:i:s', $date);
There are two ways you can implement it: you can modify it before you save it to your database, or you can add a mutator on your model.
public function setDatetimeAttribute($value)
{
$this->attributes['datetime'] = Carbon::createFromFormat('Y-m-d\TH:i:s', $value);
}
You may want to build in some validation to see which format the date/time is in before you try to convert it.
in the model you should put:
protected $dates = ['datetime'];
Use Carbon
$dt = Carbon::parse('1975-05-21 22:23:00.123456');
to save:
$model = new Model;
$model->date = $dt; // you can use the carbon object directly
$model->save();

Laravel 4 Eloquent - where timestamp is over 3 years old

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

Constant Contact API Error:"Scheduled date is before the current time."

We're currently using the API to create campaigns, and all seems to be working fine. When we try to schedule the campaign, however, we are getting errors. When we try to use the example format for 'schedule_date' from one of the SDK libraries:
$time = date('Y-m-d\TH:i:s\.000\Z', strtotime("+1 hour"));
$schedule = new Schedule();
$schedule->scheduled_date = $time;
We get an error that saying
Scheduled date is before the current time.
When we echo the $time to the screen, we see that it is in fact one hour in the future. (We are in EST).
When we try to use the standard PHP format for ISO-8601 (lowercase 'c') we get and error saying
"#/scheduled_date: Value is not a valid ISO-8601 date time format."
$dt = date('c', strtotime("+1 hour"));
schedule = new Schedule();
`$schedule->scheduled_date = $dt
I'm sure there is something obvious we are missing, so any help would be greatly appreciated.
I would definitely try using the DateTime class (http://php.net/manual/en/class.datetime.php) in conjunction with DateTimeZone to see if that alleviates the issue.
We've also updated our Date/Time parser to accept more formats, which should hopefully take care of the issue you ran into when trying to use date('c')
If you keep running into issues let me know!
Thanks,
Mike

PHP Zend date format

I want to input a timestamp in below format to the database.
yyyy-mm-dd hh:mm:ss
How can I get in above format?
When I use
$date = new Zend_Date();
it returns month dd, yyyy hh:mm:ss PM
I also use a JavaScript calender to insert a selected date and it returns in dd-mm-yyyy format
Now, I want to convert these both format into yyyy-mm-dd hh:mm:ss so can be inserted in database. Because date format not matching the database field format the date is not inserted and only filled with *00-00-00 00:00:00*
Thanks for answer
Not sure if this will help you, but try using:
// to show both date and time,
$date->get('YYYY-MM-dd HH:mm:ss');
// or, to show date only
$date->get('YYYY-MM-dd')
Technically, #stefgosselin gave the correct answer for Zend_Date, but Zend_Date is completely overkill for just getting the current time in a common format. Zend_Date is incredibly slow and cumbersome to use compared to PHP's native date related extensions. If you don't need translation or localisation in your Zend_Date output (and you apparently dont), stay away from it.
Use PHP's native date function for that, e.g.
echo date('Y-m-d H:i:s');
or DateTime procedural API
echo date_format(date_create(), 'Y-m-d H:i:s');
or DateTime Object API
$dateTime = new DateTime;
echo $dateTime->format('Y-m-d H:i:s');
Don't do the common mistake of using each and every component Zend Frameworks offers just because it offers it. There is absolutely no need to do that and in fact, if you can use a native PHP extension to achieve the same result with less or comparable effort, you are better off with the native solution.
Also, if you are going to save a date in your database, did you use any of the DateTime related columns in your database? Assuming you are using MySql, you could use a Timestamp column or an ISO8601 Date column.
This is how i did it:
abstract class App_Model_ModelAbstract extends Zend_Db_Table_Abstract
{
const DATE_FORMAT = 'yyyy-MM-dd';
public static function formatDate($date, $format = App_Model_ModelAbstract::DATE_FORMAT)
{
if (!$date instanceof Zend_Date && Zend_Date::isDate($date)) {
$date = new Zend_Date($date);
}
if ($date instanceof Zend_Date) {
return $date->get($format);
}
return $date;
}
}
this way you don't need to be concerned with whether or not its actually an instance of zend date, you can pass in a string or anything else that is a date.
a simple way to use Zend Date is to make specific function in its business objects that allows to parameter this function the date format. You can find a good example to this address http://www.pylejeune.fr/framework/utiliser-les-date-avec-zend_date/
this is i did it :
Zend_Date::now->toString('dd-MM-yyyy HH:mm:ss')
output from this format is "24-03-2012 13:02:01"
and you can modified your date format
I've always use $date->__toString('YYYY-MM-dd HH-mm-ss'); method in the past but today didn't work. I was getting the default output of 'Nov 1, 2013 12:19:23 PM'
So today I used $date->get('YYYY-MM-dd HH-mm-ss'); as mentioned above. Seems to have solved my problem.
You can find more information on this on output formats here: http://framework.zend.com/manual/1.12/en/zend.date.constants.html

Categories