Reputation: 15504
Im fetching data from a facebook user object, the birthday field have this format: MM/DD/YYYY. In Symfony2 using doctrine I define my Birthday field like:
/**
* @var \Date $birthday
*
* @ORM\Column(name="birthday", type="date", nullable=true)
*/
private $birthday;
This on the database generates the format YYYY-DD-MM, Im trying to format the facebook format into something that I can use with symfony but with no success, this is my attempt:
if(isset($fbuser["birthday"])) { //CHECK FOR FIELD birthday
$date_pz = explode('/',$fbuser["birthday"]);
// Firts try: $norm_date = array('year' => $date_pz[2], 'month' => $date_pz[0], 'day' => $date_pz[1]);
// Second try: $norm_date = $date_pz[2] .'-'. $date_pz[0] .'-'. $date_pz[1]);
$userinfo->setBirthday($norm_date); }
And Im always getting:
Fatal error: Call to a member function format() on a non-object in /var/www/vhosts/punctis.com/httpdocs/vendor/doctrine/dbal/lib/Doctrine/DBAL/Types/DateType.php on line 44
That means that im not sending the string in the format Symfony expect, so the questions here is, how to format that?
Upvotes: 3
Views: 44821
Reputation: 2145
If you have a var output like this:
echo '<pre>';
print_r($yourDateTimeObjectVar);die;
//outputs;
DateTime Object
(
[date] => 2013-12-16 15:17:27
[timezone_type] => 3
[timezone] => America/New_York
)
Then, you just have to do:
echo $yourDateTimeObjectVar->format('d/m/Y');
which will output:
16/12/2013
PS: In this case, the object came from MySql datetime column and it was insert like this:
$myOrder = new OrderStatus();
$myOrder->setDateOrder(\new DateTime());
$em->persist($myOrder);
$em->flush()
Var ORM Declaration:
@ORM\Column(name="DateOrder", type="datetime", nullable=true)
Upvotes: 4
Reputation: 5245
You should not pass a string to $userinfo->setBirthday($norm_date) but a DateTime object, try
$userinfo->setBirthday(new \DateTime($norm_date));
$userinfo->setBirthday(new \DateTime('now'));
$userinfo->setBirthday(new \DateTime('2013-01-15'));
$userinfo->setBirthday(new \DateTime('+2 days'), new \DateTimeZone('UCT'));
You can construct a DateTime object in a number of ways, check the docs here: http://php.net/manual/en/datetime.construct.php
Upvotes: 1
Reputation: 17166
The Doctrine-Type Date
is expecting a a DateTime
-object. You could use DateTime::createFromFormat()
to create said object.
Either you do it in your entity (e.g. in setBirthday($birthday)
) or create a custom DateType which does the formatting for you.
Upvotes: 3