/** * {@inheritdoc} */ public function validate($value, Constraint $constraint) { if (!$constraint instanceof DateTime) { throw new UnexpectedTypeException($constraint, __NAMESPACE__ . '\\DateTime'); } if (null === $value || '' === $value || $value instanceof \DateTime) { return; } if (!is_scalar($value) && !(is_object($value) && method_exists($value, '__toString'))) { throw new UnexpectedTypeException($value, 'string'); } $value = (string) $value; \DateTime::createFromFormat($constraint->format, $value); $errors = \DateTime::getLastErrors(); if (0 < $errors['error_count']) { $this->context->buildViolation($constraint->message)->setParameter('{{ value }}', $this->formatValue($value))->setCode(DateTime::INVALID_FORMAT_ERROR)->addViolation(); return; } foreach ($errors['warnings'] as $warning) { if ('The parsed date was invalid' === $warning) { $this->context->buildViolation($constraint->message)->setParameter('{{ value }}', $this->formatValue($value))->setCode(DateTime::INVALID_DATE_ERROR)->addViolation(); } elseif ('The parsed time was invalid' === $warning) { $this->context->buildViolation($constraint->message)->setParameter('{{ value }}', $this->formatValue($value))->setCode(DateTime::INVALID_TIME_ERROR)->addViolation(); } else { $this->context->buildViolation($constraint->message)->setParameter('{{ value }}', $this->formatValue($value))->setCode(DateTime::INVALID_FORMAT_ERROR)->addViolation(); } } }
/** * Transforms a date string in the configured timezone into a DateTime object. * * @param string $value A value as produced by PHP's date() function * * @throws TransformationFailedException If the given value is not a string, * if the date could not be parsed or * if the input timezone is not supported * * @return \DateTime|null An instance of \DateTime */ public function transform($value) { if (empty($value)) { return; } if (!is_string($value)) { throw new TransformationFailedException('Expected a string.'); } try { $outputTz = new \DateTimeZone($this->outputTimezone); $dateTime = \DateTime::createFromFormat($this->parseFormat, $value, $outputTz); $lastErrors = \DateTime::getLastErrors(); if (0 < $lastErrors['warning_count'] || 0 < $lastErrors['error_count']) { throw new TransformationFailedException(implode(', ', array_merge(array_values($lastErrors['warnings']), array_values($lastErrors['errors'])))); } if ($this->inputTimezone !== $this->outputTimezone) { $dateTime->setTimezone(new \DateTimeZone($this->inputTimezone)); } } catch (TransformationFailedException $e) { throw $e; } catch (\Exception $e) { throw new TransformationFailedException($e->getMessage(), $e->getCode(), $e); } return $dateTime; }
public function __construct($datetime, $use_raw_pattern = false, $strict = false) { if ($use_raw_pattern === false) { $pattern = OSCOM::getDef('date_time_format'); } else { $pattern = $this->raw_pattern_date . ' ' . $this->raw_pattern_time; } // format time as 00:00:00 if it is missing from the date $new_datetime = strtotime($datetime); if ($new_datetime !== false) { $new_datetime = date($pattern, $new_datetime); $this->datetime = \DateTime::createFromFormat($pattern, $new_datetime); $strict_log = false; } if ($this->datetime === false) { $strict_log = true; } else { $errors = \DateTime::getLastErrors(); if ($errors['warning_count'] > 0 || $errors['error_count'] > 0) { $this->datetime = false; $strict_log = true; } } if ($strict === true && $strict_log === true) { trigger_error('DateTime: ' . $datetime . ' (' . $new_datetime . ') cannot be formatted to ' . $pattern); } }
/** * @inheritdoc */ public function transform($value) { if (null === $value) { return null; } if (is_scalar($value)) { $value = (string) $value; } if (!is_string($value)) { throw new TransformationFailedException(sprintf('Expected a string to transform, got "%s" instead.', json_encode($value))); } if ('' === $value) { return null; } try { $outputTz = new \DateTimeZone($this->outputTimezone); $dateTime = \DateTime::createFromFormat($this->format, $value, $outputTz); $lastErrors = \DateTime::getLastErrors(); if (0 < $lastErrors['warning_count'] || 0 < $lastErrors['error_count']) { throw new TransformationFailedException(implode(', ', array_merge(array_values($lastErrors['warnings']), array_values($lastErrors['errors'])))); } } catch (\Exception $e) { throw new TransformationFailedException($e->getMessage(), $e->getCode(), $e); } return $dateTime; }
/** * Filter & validate recipients */ public function validate() { parent::validate(); $recipients = explode("\n", str_replace("\r", '', $this->getData('recipients'))); $recipients = array_unique(array_map('trim', $recipients)); $recipients = array_filter($recipients, 'strlen'); if (false === $recipients || count($recipients) < 1) { $this->addError('Recipients cannot be empty'); } try { $startDate = new DateTime($this->getData('start_date')); } catch (Exception $e) { $this->addError('Invalid Start Date'); return !$this->hasErrors(); } // Get last errors & warnings $errors = DateTime::getLastErrors(); if (!empty($errors['errors']) || !empty($errors['warnings'])) { $this->addError('Invalid Start Date'); } // Set filtered & validated state $this->setData('recipients', $recipients); $this->setData('start_date', $startDate->format(Varien_Date::DATETIME_PHP_FORMAT)); return !$this->hasErrors(); }
public function parseDateValue($value) { $res = false; if (preg_match('/^\\d\\d\\d\\d-\\d\\d-\\d\\d( \\d\\d:\\d\\d(:\\d\\d){0,1}){0,1}$/', $value, $matches)) { switch (count($matches)) { case 1: if (!$this->time_required) { $res = DateTime::createFromFormat('Y-m-d H:i:s', $value . ' 00:00:00'); } break; case 2: $res = DateTime::createFromFormat('Y-m-d H:i:s', $value . ':00'); break; case 3: $res = DateTime::createFromFormat('Y-m-d H:i:s', $value); break; default: $res = false; } } // check there were no warnings because of invalid date values (strict checking) if ($res) { $errs = DateTime::getLastErrors(); if (!empty($errs['warning_count'])) { $res = false; } } return $res; }
public function run($value) { \DateTime::createFromFormat($this->format, $value); $errors = \DateTime::getLastErrors(); if (count($errors['warnings']) || count($errors['errors'])) { $this->addError('must_be_datetime_format', $this->format); } }
public function testCreateFromFormatFailure() { $time = 'foo'; $immutable = DateTimeImmutable::createFromFormat(DateTime::RFC3339, $time); $mutable = DateTime::createFromFormat(DateTime::RFC3339, $time); $this->assertFalse($immutable); $this->assertSame(DateTime::getLastErrors(), DateTimeImmutable::getLastErrors()); }
/** * Overcoming a PHP \DateTime poor design choice. * * @param \DateTime $dateTime * @return bool */ public static function dateTimeIsValid(\DateTime $dateTime) { try { \DateTime::createFromFormat(\DateTime::ISO8601, $dateTime->format(\DateTime::ISO8601)); } catch (\Exception $e) { return false; } return \DateTime::getLastErrors()['warning_count'] == 0 && \DateTime::getLastErrors()['error_count'] == 0; }
public function getDate($value, $format) { $date = \DateTime::createFromFormat($format, $value); $lastRes = \DateTime::getLastErrors(); if ($lastRes['warning_count'] != 0 || $lastRes['error_count'] != 0) { return false; } return $date; }
/** * This function helps with Date * @param array $columns represents an array of columns. * foreach $column in columns = array( 'heading' => 'Name Of Column', 'rows' => array('id' => 'data'), 'action' => false || 'action' = array('Controller'=>'action') ); */ public function datef($date, $error_string = 'Invalid Date', $format = DATE_STANDARD) { $temp = new DateTime($date); $error = DateTime::getLastErrors(); if (empty($date) || $error['warning_count'] > 0 || $error['error_count'] > 0) { return __($error_string); } return $temp->format($format); }
/** * Check if a string is a valid date(time) * * @link http://www.pontikis.net/tip/?id=21 * * @param string $dateStr * @param string $dateFormat * @param string $timezone (If timezone is invalid, php will throw an exception) * @return bool */ function isValidDateTimeString($dateStr, $dateFormat, $timezone = null) { if ($timezone) { $date = \DateTime::createFromFormat($dateFormat, $dateStr, new \DateTimeZone($timezone)); } else { $date = \DateTime::createFromFormat($dateFormat, $dateStr); } return $date && \DateTime::getLastErrors()["warning_count"] == 0 && \DateTime::getLastErrors()["error_count"] == 0; }
public function string_to_datetime($string) { $date = date_create(str_replace('.000000', '', $string)); $errors = \DateTime::getLastErrors(); if ($errors['warning_count'] > 0 || $errors['error_count'] > 0) { return null; } return $date; }
/** * Returns new DateTime object formatted according to the specified format * * @param string $format The format that the passed in string should be in * @param string $time String representing the time * @return \DateTime * @throws Exception\InvalidDateStructureException If creation fail */ public static function createFromFormat($format, $time) { if ($dateTime = \DateTime::createFromFormat($format, $time)) { return $dateTime; } $errors = \DateTime::getLastErrors(); $msg = trim(implode(', ', array_merge($errors['errors'], $errors['warnings']))); throw new Exception\InvalidDateStructureException($msg); }
public static function createDateTime($format, $stringDateTime) { $dateTime = \DateTime::createFromFormat($format, $stringDateTime); $dateErrors = \DateTime::getLastErrors(); if ($dateErrors['warning_count'] + $dateErrors['error_count'] > 0) { return false; } return $dateTime; }
/** * @return \DateTime|NULL */ public function getValue() { $value = parent::getValue(); $value = \DateTime::createFromFormat(static::$format, $value); $err = \DateTime::getLastErrors(); if ($err['error_count']) { $value = FALSE; } return $value ?: NULL; }
/** * Create Data from a specific format * * @return mixed * @since 1.0.0 */ protected function createFromFormat() { $format = $this->getOption('create_from_format', $this->default_format); $formatted_value = DateTime::createFromFormat($format, $this->field_value); $errors = DateTime::getLastErrors(); if ($errors['warning_count'] > 0) { return false; } return $formatted_value; }
/** * Create a new Date. * * @param Year $year * @param Month $month * @param MonthDay $day * * @throws InvalidDateException */ public function __construct(Year $year, Month $month, MonthDay $day) { \DateTime::createFromFormat('Y-F-j', \sprintf('%d-%s-%d', $year->toNative(), $month, $day->toNative())); $nativeDateErrors = \DateTime::getLastErrors(); if ($nativeDateErrors['warning_count'] > 0 || $nativeDateErrors['error_count'] > 0) { throw new InvalidDateException($year->toNative(), $month->toNative(), $day->toNative()); } $this->year = $year; $this->month = $month; $this->day = $day; }
public static function verify($date, $format = 'Y-m-d', $strict = true) { $dateTime = \DateTime::createFromFormat($format, $date); if ($strict) { $errors = \DateTime::getLastErrors(); if (!empty($errors['warning_count'])) { return false; } } return $dateTime !== false; }
protected function _validate($value) { if ($value instanceof \DateTime) { return; } $date = \DateTime::createFromFormat($this->_format, $value); $errors = \DateTime::getLastErrors(); if ($errors['warning_count'] || $errors['error_count']) { $this->error(); } }
function validDate($date, $strict = true) { $dateTime = DateTime::createFromFormat('Y-m-d', $date); if ($strict) { $errors = DateTime::getLastErrors(); if (!empty($errors['warning_count'])) { return false; } } return $dateTime !== false; }
public static function isTimeInValidFormat($time) { $dateTime = DateTime::createFromFormat('H:i', $time); if (!$dateTime) { return false; } $errors = DateTime::getLastErrors(); if (!empty($errors['warning_count'])) { return false; } return true; }
private function createFromFormat($value) { $dateFormats = array('Y-m-d H:i:s', 'd/m/Y', 'd/m/y', 'd/m/Y H:i:s', 'd/m/Y H:i'); foreach ($dateFormats as $format) { $date = \DateTime::createFromFormat($format, $value); $errors = \DateTime::getLastErrors(); if ($errors['warning_count'] === 0 && $date != false) { return $date; } } return null; }
protected function parseDate($format, $dateStr) { if (empty($dateStr)) { return null; } $date = \DateTime::createFromFormat($format, $dateStr); $errors = \DateTime::getLastErrors(); if ($errors['error_count'] > 0) { throw new \Exception("Error on date '{$dateStr}', expected format '{$format}' : " . implode(" ", $errors['errors'])); } return $date; }
/** * Converts a time string to a timestamp * @param string $string The time string * @param string $format The string format * @return int The timestamp */ public static function stringToTimestamp($string, $format = DateTool::FORMAT_MYSQL_DATETIME) { if (!is_string($string)) { throw new Exception('Unable to convert time string to timestamp : "' . $string . '" is not a string'); } $var = DateTime::createFromFormat($format, $string); if ($var instanceof DateTime) { return $var->getTimestamp(); } LogTool::getInstance()->logWarning("DateTime::createFromFormat returned errors."); LogTool::getInstance()->logDebug("debug " . serialize(DateTime::getLastErrors())); return false; }
function validateDate($date) { $slashDelim = explode('/', $date); $dashDelim = explode('-', $date); $spaceDelim = explode(' ', $date); $stringFormat = 'Y/m/d'; if (count($dashDelim) > 1) { $stringFormat = 'Y-m-d'; } elseif (count($spaceDelim) > 1) { $stringFormat = 'Y m d'; } $date = DateTime::createFromFormat($stringFormat, $date); return $date && DateTime::getLastErrors()['warning_count'] == 0 && DateTime::getLastErrors()['error_count'] == 0; }
/** * @param \DateTime|MomentPHP|string|int|null $dateTime Instance of classes \DateTime or MomentPHP or string representing the time or timestamp or null for now. * @param array|string|null $format Field formats or simple formatting options, see http://php.net/manual/en/datetime.createfromformat.php * @param \DateTimeZone|string|null $timeZone Supported Timezones, see http://php.net/manual/en/timezones.php * @throws InvalidArgumentException */ public function __construct($dateTime = null, $format = null, $timeZone = null) { $this->validateDateTime($dateTime); $this->validateFormat($format); $this->validateTimeZone($timeZone); $timeZone = $this->createDateTimeZone($timeZone); try { // set dateTime by type if (!isset($dateTime)) { $this->dateTime = new \DateTime('now', $timeZone); } elseif ($dateTime instanceof \DateTime) { $this->dateTime = $dateTime; } elseif ($dateTime instanceof MomentPHP) { $this->dateTime = $dateTime->dateTime; } elseif (is_string($dateTime)) { $this->dateTime = $this->fromFormat($dateTime, $format, $timeZone); } elseif (is_int($dateTime)) { $this->dateTime = $this->fromFormat($dateTime, 'U', $timeZone); } } catch (\Exception $e) { throw new InvalidArgumentException($e->getMessage()); } $error = $this->dateTime->getLastErrors(); if ($error['warning_count'] > 0) { $msg = 'WARNINGS: ' . join('; ', $error['warnings']); throw new InvalidArgumentException($msg); } if ($error['error_count'] > 0) { $msg = 'ERRORS: ' . join('; ', $error['errors']); throw new InvalidArgumentException($msg); } }
/** * Checks if $dateTime is a valid date-time object, and if the formatted date is the same as the value passed. * * @param \DateTime $dateTime * @param string $format * @param mixed $value * @return \DateTime|false */ protected function checkDate($dateTime, $format, $value) { if ($dateTime->getLastErrors()['warning_count'] === 0 && $dateTime->format($format) === $value) { return $dateTime; } return false; }
/** * Validates input. * * @param mixed $input * * @return bool */ public function isValid($input = null) { if ($input === null || $input === '') { return false; } $input = (string) $input; PhpDateTime::createFromFormat(static::FORMAT, $input); $errors = PhpDateTime::getLastErrors(); if ($errors['error_count'] > 0) { $this->violations[] = 'format'; return false; } foreach ($errors['warnings'] as $warning) { if ($warning === 'The parsed date was invalid') { $this->violations[] = 'date'; } else { if ($warning === 'The parsed time was invalid') { $this->violations[] = 'time'; } else { $this->violations[] = 'format'; } } } return !$this->hasViolations(); }
/** * Checks if a value is a a valid datetime format. * * @param string|\DateTime $value * * @return bool */ public static function isDateTime($value) { if ($value instanceof \DateTime) { return true; } $date = new \DateTime($value); $errors = $date->getLastErrors(); return 0 == $errors['warning_count'] && 0 == $errors['error_count']; }