Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
branch: master
Fetching contributors…

Octocat-spinner-32-eaf2f5

Cannot retrieve contributors at this time

file 68 lines (61 sloc) 1.821 kb
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67
<?php
/**
* Extends PHP's DateTime class to support date and time setting from format.
* This functionality is rather similar than Zend_Date's setTime() and
* setDate() methods.
*
* @category Kblom
* @package Kblom_Date
* @uses Kblom_Validate_Datetime
* @copyright Copyright (c) 2010-2011 Kim Blomqvist
* @license http://github.com/kblomqvist/kblom-zf1/raw/master/LICENSE The MIT License
*/
class Kblom_Date extends DateTime
{
/** @var Kblom_Validate_Datetime */
protected $_datetimeValidator;

/**
* Set date, time or datetime from format
*
* Example:
* $date = new Kblom_Date('2011-01-01');
* echo $date->setFromFormat('H:i', '10:45'); // '2011-01-01 10:45:00'
* echo $date->setFromFormat('n', 4); // '2011-04-01 10:45:00'
*
* @param string $format
* @param int|string $time
*/
public function setFromFormat($format, $time)
{
$validator = $this->_getDatetimeValidator();
if (!$validator->isValid($time, $format)) {
throw new Exception('Invalid time in given format');
}

$parts = array(
'day' => $this->format('j'),
'month' => $this->format('n'),
'year' => $this->format('Y'),
'hour' => $this->format('G'),
'minute' => $this->format('i'),
'second' => $this->format('s')
);
$parts = array_merge($parts, $validator->getMatchedParts());

return $this->setDate($parts['year'], $parts['month'], $parts['day'])
->setTime($parts['hour'], $parts['minute'], $parts['second']);
}

protected function _getDatetimeValidator()
{
if (!isset($this->_datetimeValidator)) {
$this->_datetimeValidator = new Kblom_Validate_Datetime();
}
return $this->_datetimeValidator;
}

public function toString($format)
{
return $this->format($format);
}

public function __toString()
{
return $this->format('Y-m-d H:i:s');
}
}
Something went wrong with that request. Please try again.