DateTimeType.php 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. <?php
  2. /**
  3. * PHP Version 5.4
  4. *
  5. * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
  6. * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
  7. *
  8. * Licensed under The MIT License
  9. * For full copyright and license information, please see the LICENSE.txt
  10. * Redistributions of files must retain the above copyright notice.
  11. *
  12. * @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
  13. * @link http://cakephp.org CakePHP(tm) Project
  14. * @since CakePHP(tm) v 3.0.0
  15. * @license MIT License (http://www.opensource.org/licenses/mit-license.php)
  16. */
  17. namespace Cake\Database\Type;
  18. use Cake\Database\Driver;
  19. use \DateTime;
  20. /**
  21. * Datetime type converter.
  22. *
  23. * Use to convert datetime instances to strings & back.
  24. */
  25. class DateTimeType extends \Cake\Database\Type {
  26. /**
  27. * Convert DateTime instance into strings.
  28. *
  29. * @param string|Datetime $value The value to convert.
  30. * @param Driver $driver The driver instance to convert with.
  31. * @return string
  32. */
  33. public function toDatabase($value, Driver $driver) {
  34. if (is_string($value)) {
  35. return $value;
  36. }
  37. return $value->format('Y-m-d H:i:s');
  38. }
  39. /**
  40. * Convert strings into DateTime instances.
  41. *
  42. * @param string $value The value to convert.
  43. * @param Driver $driver The driver instance to convert with.
  44. * @return Datetime
  45. */
  46. public function toPHP($value, Driver $driver) {
  47. if ($value === null) {
  48. return null;
  49. }
  50. $value = DateTime::createFromFormat('Y-m-d H:i:s', $value);
  51. return $value;
  52. }
  53. }