Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

210
Vistas
How to get only the date from a DateTime object?

I have a variable of type DateTime() and I want to get only the date of it to compare it with an other date variable. Here is how I tried to do that, but I get extra data that I don't need:

date_default_timezone_set('Africa/Tunis');
$date= new \DateTime('today');
$date->format('d/m/Y');

var_dump($date) returns : object(DateTime)#617 (3) { ["date"]=> string(19) "2017-04-09 00:00:00" ["timezone_type"]=> int(3) ["timezone"]=> string(12) "Africa/Tunis" } So I want to get something like this : 09/04/2017

UPDATE: This is my action code (I have a form in twig that contains a date type input) :

 public function addArtAction(Request $request)
    {

        $article=new article();
        $em=$this->getDoctrine()->getManager();
        $title=$request->request->get('titre');
        $content=$request->files->get('contenu');
        $dtePub=$request->request->get('date');
        date_default_timezone_set('Africa/Tunis');
        $datee= new \DateTime('today');
        $date=$datee->format('d/m/Y');

        if($dtePub==$date)
        {
            $article->setTitre($title);
            $article->setCorps($content);
            $article->setEtat(true);
            $article->setDtePub($date);
            $em->persist($article);
            $em->flush();
            $this->get('session')->getFlashBag()->add('success','Votre article a été archivé!');
        }
        elseif($dtePub>$date)
        {
        $article->setTitre($title);
        $article->setCorps($content);
        $article->setEtat(false);
        $article->setDteArch($date);
        $article->setDtePub($dtePub);
        $em->persist($article);
        $em->flush();
        $this->get('session')->getFlashBag()->add('success','Votre article a été publié avec succès!');
        }
        elseif($dtePub<$date)
        {
            $this->get('session')->getFlashBag()->add('failure','Vous devez choisir une future date!');
        }
        var_dump($date);

    }
about 4 years ago · Santiago Trujillo
3 Respuestas
Responde la pregunta

0

You were doing it (almost right). For reference here a copy-paste your code:

date_default_timezone_set('Africa/Tunis');
$date= new \DateTime('today');
$date->format('d/m/Y');

The last line returns the desired string. If you want to output that you can just echo it:

echo $date->format('d/m/Y');

Basically your misunderstanding was that the format method does not modify the $date object, but only return the desired string. If you look at the documentation for the format method you will find:

Returns date formatted according to given format

It says "returns" with which means returned to the context of the call: the expression of the call 'is substituted' by the returned value. If it would output it in the function, then the manual would have said something like "prints" or "outputs" or "dumps". You can read more about what 'returning a value' means in this part of the manual. The first example shows the exact equivalent of what you tried to do:

Example #1 Use of return

<?php function square($num) {
  return $num * $num;
}
echo square(4);   // outputs '16'.
?>

Lastly, with regards to the use of var_dump: please note that this is intended for debugging purposes and normally not for displaying output to the user. var_dump will normally just dump "All public, private and protected properties of objects" of the given object. You should check the var_dump manual pages it contains many examples.

about 4 years ago · Santiago Trujillo Denunciar

0

Use format:

$date->format('d/m/Y');

or

$date->format('m/d/Y');

(I don't know your locale preferences)

about 4 years ago · Santiago Trujillo Denunciar

0

If you need to compare to another date timestamp just convert it like this:

<?php
  $literal = "1 week ago";
  $date = new DateTime($literal);
  $date->setTime(0,0);

  $timestamp = $date->getTimestamp();
?>
about 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda