Display Datetime Content Using Doctrine

2

In a WebService project using SlimFramework, I decided to add Doctrine to do the queries in the DB. I resolved to follow DOCTRINE's guidance for working with Datetime and Time Zones on this site Doctrine Documentation

When trying to recover the value of the bank I used the following code:

  try{
    $repository = $entityManager->getRepository(User::class);
    $usuarios = $repository->findAll();

    foreach ($usuarios as $usuario){
        var_dump( $usuario->getUserDthActivation()) .  "<br/>";
    }
    die;
    return $response
        ->withHeader("Content-Type", "application/json")
        ->write(json_encode($usuarios, JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT));
}catch (Exception $e){

}

The printed result was as follows:

  

object (DateTimeZone) # 138 (2) {["timezone_type"] = > int (3)   ["timezone"] = > string (17) "America / Sao_Paulo"} object (DateTime) # 140   (3) {["date"] = > string (26) "2012-07-01 08: 36: 35.000000"   ["timezone_type"] = > int (3) ["timezone"] = > string (17)   "America / Sao_Paulo"}

In my case I only need information 01-07-2012 08:07:35

What is the correct way to display only the date content in dd-mm-YY format hh: mm: ss?

The file that does this processing is as follows:

class UTCDateTimeType extends DateTimeType
{
/** @var \DateTimeZone */
static private $utc = null;

/**
 * {@inheritDoc}
 */
public function convertToDatabaseValue($value, AbstractPlatform $platform)
{
    if ($value === null) {
        return null;
    }

    if (!$value instanceof \DateTime) {
        return null;
    }

    $value->setTimezone((self::$utc) ? self::$utc : (self::$utc = new \DateTimeZone('UTC')));

    return $value->format($platform->getDateTimeFormatString());
}

/**
 * {@inheritDoc}
 */
public function convertToPHPValue($value, AbstractPlatform $platform)
{

    if ($value === null) {
        return null;
    }

    $val = \DateTime::createFromFormat(
        $platform->getDateTimeFormatString(),
        $value,
        (self::$utc) ? self::$utc : (self::$utc = new \DateTimeZone('UTC'))
    );

    if (!$val) {
        throw ConversionException::conversionFailed($value, $this->getName());
    }

    return $val;
  }
}
    
asked by anonymous 21.09.2016 / 02:16

1 answer

2

If $usuario->getUserDthActivation() returns a DateTime valid, you can improve the return doing so:

$usuario->getUserDthActivation()->format('d-m-Y H:i:s');

Reference:

21.09.2016 / 18:02