Normally datetime is stored UTC. Cast to local datetime as needed for things like this. This can all be done via PHP or Laravel with carbon.
Is it necessary to cast date in mysql for comparison?
e.g, getting items that have been created today:
$query->where('created_at', '>', now()->startOfDay())
->where('created_at', '<', now()->endOfDay());
$query->whereDate('created_at', '>', now()->startOfDay())
->whereDate('created_at', '<', now()->endOfDay());
Are there any differences when comparing datetime columns in mysql with date(created_at) cast or without?
@amir5 casting has nothing to do with the mysql query. It should always be in YYYY-MM-DD format. Cast is when you want to present it to your users differently, like:
02/20/2025
But have it in the correct format to store or to query. Like:
2025-02-20
I don't even know why laravel calls it casting, it's just formatting it a certain way.
Example, when it reaches here it's in the correct format passed from controller:
public function getChecks($offset = "", $rowsperpage = "", $checksearch = "", $searchby = null)
{
if ($searchby === "checkdate") {
//$date_start = \DateTime::createFromFormat('Y-m-d', $checksearch);
$pagingQuery = " LIMIT $offset, $rowsperpage";
$sql = "SELECT checkid, transdate, transdescribe, widthdraw, deposit, isclr";
$sql = $sql . " FROM checks";
$sql = $sql . " WHERE `transdate` = :datestart";
$sql = $sql . " ORDER BY checkid" . $pagingQuery;
$sth = $this->db->pdoPrepare($sql);
$params = [':datestart' => $checksearch];
$sth->execute($params);
$results = $sth->fetchAll(\PDO::FETCH_ASSOC);
return $results;
}
// other criteria as needed
It's from a custom framework, but the idea of passing for example 2024-12-15 as a date is the same for laravel, cakephp, java, python, etc if working with mysql.
Please or to participate in this conversation.