PHP code example of herrera-io / doctrine-dateinterval

1. Go to this page and download the library: Download herrera-io/doctrine-dateinterval library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

herrera-io / doctrine-dateinterval example snippets




use Doctrine\DBAL\Types\Type;
use Herrera\Doctrine\DBAL\Types\DateIntervalType;

Type::addType(
    DateIntervalType::DATEINTERVAL,
    'Herrera\\Doctrine\\DBAL\\Types\\DateIntervalType'
);



$entityManager->getConfiguration()->addCustomDatetimeFunction(
    'DATE_INTERVAL',
    'Herrera\\Doctrine\\ORM\\Query\\AST\\Functions\\DateIntervalFunction'
);

$entityManager->getConnection()
              ->getDatabasePlatform()
              ->registerDoctrineTypeMapping(
    DateIntervalType::DATEINTERVAL,
    DateIntervalType::DATEINTERVAL
);



/**
 * @Entity()
 * @Table(name="Jobs")
 */
class Job
{
    /**
     * @Column(type="integer")
     * @GeneratedValue(strategy="AUTO")
     * @Id()
     */
    private $id;

    /**
     * @Column(type="dateinterval")
     */
    private $interval;

    /**
     * @return DateInterval
     */
    public function getInterval()
    {
        return $this->interval;
    }

    /**
     * @param DateInterval $interval
     */
    public function setInterval(DateInterval $interval)
    {
        $this->interval = $interval;
    }
}

$annualJob = new Job();
$annualJob->setInterval(new DateInterval('P1Y'));

$monthlyJob = new Job();
$monthlyJob->setInterval(new DateInterval('P1M'));

$dailyJob = new Job();
$dailyJob->setInterval(new DateInterval('P1D'));

$entityManager->persist($annualJob);
$entityManager->persist($monthlyJob);
$entityManager->persist($dailyJob);
$entityManager->flush();
$entityManager->clear();

$jobs = $entityManager->createQuery(
    "SELECT j FROM Jobs j WHERE j.interval < DATE_INTERVAL('P1Y') ORDER BY j.interval ASC"
)->getResult();

echo $jobs[0]->getInterval()->toSpec(); // "P1D"
echo $jobs[1]->getInterval()->toSpec(); // "P1M"