Wednesday 20 July 2011

PHP Doctrine 2: Convert UK date string to datetime

You have a form with a date field, and on submit you want to save the value as a Doctrine Datetime. You may find PHP's strtotime() function, but this will only work for dates in the US format (e.g. mm/dd/yyyy) and not the UK format (e.g. dd/mm/yyyy). The solution is to use DateTime::createFromFormat() which lets you specify the way the date string is formatted.
$result = DateTime::createFromFormat("d/m/Y", $dateString);
This can then be set as your datetime property on your entity, and persisted in the database. You can see which letters to use to represent your date format here.

No comments:

Post a Comment