Converting a datetime to text does not show the result

2

I have a date in this format: Quarta, 21 Maio, 2014 .

To save this date in the database I'm converting it to datetime as follows:

$f['data'] = $_POST['data'];
$data = DateTime::createFromFormat('l, j F, Y', $f['data']); 
$data = $data->format('Y-m-d H:i:s'); 

Then I insert the variable $data into my table and it works correctly. The date is saved as datetime in the database.

But now I want to show the date, and I want to turn it back into the format Quarta, 21 Maio, 2014 .

So I'm doing my select and then reusing DateTime::createFormat to convert the date from datetime to the text format I want:

$lerNoticia = $pdo->prepare("SELECT * FROM noticias WHERE");
$lerNoticia->execute();
while ($lerNoticiaResult  = $lerNoticia->fetch(PDO::FETCH_ASSOC))
{
   $data = DateTime::createFromFormat('l, j F, Y', $lerNoticiaResult['data']);
   ..... //tenho aqui mais echos a mostrar o titulo da noticia, etc
   echo '<span class="data">'.$data.'</span>';
}

The problem is that the date is not appearing, what can I do wrong?

    
asked by anonymous 21.05.2014 / 21:11

3 answers

1

You have to do the reverse. To store, you created a DateTime object, formatted it in String on sent to base. The base will return a String if the type is datetime (I think it is) and you will have to create a new object from this format:

$data = DateTime::createFromFormat('Y-m-d H:i:s', $lerNoticiaResult['data']);

and then format the output in String:

$data = $data->format('l, j F, Y');

Personally I do not use this class much, so the answer may not be very accurate, but the logic is this.

    
21.05.2014 / 23:18
1

I had some problems saving dates in Datetime in Doctrine , I solved it as follows:

    static function strToDatetime($strDate)
        {
            $strDate = str_replace('/', '-', $strDate);
            $datetime = new \DateTime(date('Y-m-d', strtotime($strDate)));
            $datetime->format('Y-m-d');

            return $datetime;
        }

The function receives a date in the form of text;

I used str_replace('/', '-', $strDate); because my date came with - of the form instead of bars (ex: 10-05-1996 );

Then the function creates a DateTime object with the date in question and returns this object.

    
21.05.2014 / 22:21
1

I do this:

<?php echo date('d-m-Y H:i:s', strtotime($datadobanco) ); ?>

In the first parameter you should use the format according to this reference:
link

Thanks

    
23.05.2014 / 00:06