Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using DateTime::CreateFromFormat to create a date object

Tags:

php

datetime

I have a string of a date:

25/08/2012

And here I'm trying to convert it to a DateTime object in order to save it to the MySQL database. My backend schema has a DateOfPrint date column ready to receive this data.

Here's what I've tried:

$eventDate = DateTime::createFromFormat('d/m/y', $fecha->innertext);
echo $eventDate;

The echo statement doesn't show anything on the screen, and when trying to save it to the database, nothing is saved in that column.

Any suggestions?

like image 668
sergserg Avatar asked Dec 09 '22 21:12

sergserg


2 Answers

Your $eventDate contains a boolean(false) which is printed as empty string.

You need to use an upper-case Y.

Y   A full numeric representation of a year, 4 digits    Examples: 1999 or 2003
y   A two digit representation of a year    Examples: 99 or 03

And you have to call DateTime::format();
e.g.

<?php
$fecha = new StdClass;
$fecha->innertext = '25/08/2012';

$eventDate = DateTime::createFromFormat('d/m/Y', $fecha->innertext);
if ( false===$eventDate ) {
  die('invalid date format');
}
echo $eventDate->format('Y-m-d');

prints

2012-08-25
like image 71
VolkerK Avatar answered Dec 27 '22 15:12

VolkerK


You need to format it for a MySQL column before you can insert it:

// Need upper case Y here, thanks to VolkerK for pointing that out
$eventDate = DateTime::createFromFormat('d/m/Y', $fecha->innertext);
$eventDate = $eventDate->format( 'Y-m-d'); // I think this is the correct format

Then you can use $eventDate to save the date to the database.

like image 31
nickb Avatar answered Dec 27 '22 17:12

nickb