(Hi), I need to find all my objects from a date formated at (mm-yyyy), problem is than formated date are string and I can't compare dateTime objects and strings.
Could not convert PHP value '03-2019' of type 'string' to type 'datetime'. Expected one of the following types: null, DateTime
I show you my code :
/**
* @Route("/month/{date}", name="monthly_resume", methods={"GET"})
* @param RentReleaseRepository $rentReleaseRepository
* @param $date
* @return Response
*/
public function monthlyCalcul(RentReleaseRepository $rentReleaseRepository, $date)
{
if (substr($date, 0, 7) === 'Janvier') {
$date = str_replace('01-', 'Janvier ', $date);
} elseif (substr($date, 0, 7) === 'Février') {
$date = str_replace('02-', 'Février ', $date);
} elseif (substr($date, 0, 4) === 'Mars') {
$date = str_replace('03-', 'Mars ', $date);
} elseif (substr($date, 0, 5) === 'Avril') {
$date = str_replace('04-', 'Avril ', $date);
} elseif (substr($date, 0, 3) === 'Mai') {
$date = str_replace('05-', 'Mai ', $date);
} elseif (substr($date, 0, 4) === 'Juin') {
$date = str_replace('06-', 'Juin ', $date);
} elseif (substr($date, 0, 7) === 'Juillet') {
$date = str_replace('07-', 'Juillet ', $date);
} elseif (substr($date, 0, 4) === 'Août') {
$date = str_replace('08-', 'Août ', $date);
} elseif (substr($date, 0, 9) === 'Septembre') {
$date = str_replace('09-', 'Septembre ', $date);
} elseif (substr($date, 0, 7) === 'Octobre') {
$date = str_replace('10-', 'Octobre ', $date);
} elseif (substr($date, 0, 7) === 'Novembre') {
$date = str_replace('110-', 'Novembre ', $date);
} elseif (substr($date, 0, 8) === 'Décembre') {
$date = str_replace('12-', 'Décembre ', $date);
} else {
throw new LogicException('OK ... So ... There is a problem');
}
$currentDate = new \DateTime();
$currentDate = $currentDate->format('m-Y');
$rentRelease = $rentReleaseRepository->findBy(
[
'userRentRelease' => $this->getUser(),
'date' => $currentDate, // the problem is here
]
);
//TODO calcul algorithm
return $this->render('resume_page/month.html.twig', [
'date' => $date
]);
}
To create my date I did it:
$rentRelease->setDate(new \DateTime());
Of course there is an issue to this problem, but I don't have any idea about how to resolve it... Your help is appreciated :)
Change $currentDate = $currentDate->format('m-Y');
to $currentDate = $currentDate->format("Y-m") . "-01 00:00:00";
but you must define your logic code like
// use $year and $mounth as parameter !
if (!is_numeric($year)) $year = date('Y');
if (!is_numeric($mounth)) $mounth = date('m');
$currentDate = DateTime::createFromFormat("Y-m-d", $year . "-" . $mounth.'-15');
$start_mounth = $currentDate->format("Y-m") . "-01 00:00:00";
$end_mounth = $currentDate;
$end_mounth->add(new DateInterval('P01M'));
$end_mounth = $end_mounth->format("Y-m") . "-01 00:00:00";
and in your logic sql you define
->andWhere('e.date BETWEEN :start AND :end')
->setParameter('start', $start_mounth )
->setParameter('end', $end_mounth)