Converting a datetime to text does not show the result

Asked

Viewed 318 times

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 insert the variable $data in my table and 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 mine select and then to use the DateTime::createFormat to convert the date of datetime for 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 date’s not showing up, which I might be doing wrong?

3 answers

1

I had some problems saving dates on Datetime in the Doctrine, I resolved 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 text form;

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

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

  • Thank you William for the answer, I expressed with your function and it worked. But I was really trying with datetime! However with the help of user692 I have already succeeded in doing this. Thank you!

1


You have to do the reverse way. To store, you created a Datetime object, formatted in String in sent to the base. The base will return a String if the type is datetime (I think it is) and you will have to create 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 don’t use this class very much, so the answer may not be very precise, but the logic is this.

1

  • Thanks, it worked, but I accepted the answer of user6492, because I was trying to use the class Datetime.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.