(Привет), Мне нужно найти все мои объекты по дате, отформатированной в (мм-гггг), проблема в том, что отформатированная дата является строкой, и я не могу сравнивать объекты и строки dateTime.
Could not convert PHP value '03-2019' of type 'string' to type 'datetime'. Expected one of the following types: null, DateTime
Я показываю вам свой код:
/**
* @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
]);
}
Чтобы создать дату, я сделал это:
$rentRelease->setDate(new \DateTime());
Конечно, в этой проблеме есть проблема, но я понятия не имею, как ее решить... Ваша помощь приветствуется :)
хорошо, а как насчет часов, минут и секунд?
$currentDate->format('m-Y') возвращает строку. Вы не можете использовать строку для сравнения с датой и временем в вашем findBy, отправьте свой объект DateTime без форматирования.






Вы можете попробовать изменить это:
$rentRelease = $rentReleaseRepository->findBy(
[
'userRentRelease' => $this->getUser(),
'date' => $currentDate, // the problem is here
]
);
К этому
$startDate = new \DateTime('01-'.$date.' 00:00:00');
$endDate = (clone $startDate)->modify('+ 1 month - 1 second');
$rentRelease = $rentReleaseRepository->createQueryBuilder('rent')
->where('userRentRelease = :user')
->andWhere('date BETWEEN :dateFrom AND :dateTo')
->setParameters([
'user' => $this->getUser(),
'dateFrom' => $startDate,
'dateTo' => $endDate,
])
->getQuery()
->getResult();
Изменить $currentDate = $currentDate->format('m-Y'); на $currentDate = $currentDate->format("Y-m") . "-01 00:00:00";
но вы должны определить свой логический код, например
// 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";
и в вашей логике sql вы определяете
->andWhere('e.date BETWEEN :start AND :end')
->setParameter('start', $start_mounth )
->setParameter('end', $end_mounth)
сделай все первого числа месяца и сравни