本文整理汇总了PHP中IntlDateFormatter::parse方法的典型用法代码示例。如果您正苦于以下问题:PHP IntlDateFormatter::parse方法的具体用法?PHP IntlDateFormatter::parse怎么用?PHP IntlDateFormatter::parse使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类IntlDateFormatter
的用法示例。
在下文中一共展示了IntlDateFormatter::parse方法的14个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。
示例1: evaluateAttributes
public function evaluateAttributes($event)
{
if (strncmp($this->sourceFormat, 'php:', 4) === 0) {
$sourceFormat = FormatConverter::convertDatePhpToIcu(substr($this->sourceFormat, 4));
} else {
$sourceFormat = $this->sourceFormat;
}
$formatter = new \IntlDateFormatter(Yii::$app->formatter->locale, null, null, Yii::$app->formatter->timeZone, Yii::$app->formatter->calendar, $sourceFormat);
foreach ($this->attributes as $attribute) {
$value = $this->owner->{$attribute};
if (empty($value)) {
continue;
}
$this->owner->{$attribute} = Yii::$app->formatter->asDateTime($formatter->parse($value), $this->destinationFormat);
}
}
示例2: createDateTime
/**
* Creates date time object from date string
*
* @param string $dateString
* @param string|null $timeZone
* @param string $format
* @throws \Exception
* @return \DateTime
*/
private function createDateTime($dateString, $timeZone = null, $format = 'yyyy-MM-dd')
{
$pattern = $format ? $format : null;
if (!$timeZone) {
$timeZone = date_default_timezone_get();
}
$calendar = \IntlDateFormatter::GREGORIAN;
$intlDateFormatter = new \IntlDateFormatter(\Locale::getDefault(), \IntlDateFormatter::NONE, \IntlDateFormatter::NONE, $timeZone, $calendar, $pattern);
$intlDateFormatter->setLenient(false);
$timestamp = $intlDateFormatter->parse($dateString);
if (intl_get_error_code() != 0) {
throw new \Exception(intl_get_error_message());
}
// read timestamp into DateTime object - the formatter delivers in UTC
$dateTime = new \DateTime(sprintf('@%s UTC', $timestamp));
if ('UTC' !== $timeZone) {
try {
$dateTime->setTimezone(new \DateTimeZone($timeZone));
} catch (\Exception $e) {
throw new \Exception($e->getMessage(), $e->getCode(), $e);
}
}
return $dateTime;
}
示例3: normalize
/**
* Convert localized string representations to integer, float or date values
*
* Subclasses can support localized input formats by calling this method
* from a filter.
*
* Non-string values get trimmed and converted to integer, float or
* \DateTime, depending on $type. Invalid values are returned as string. The
* input filter should validate filtered data by checking the datatype via
* validateType().
*
* @param string $value Localized input string
* @param string $type Data type (integer, float, date). Any other value will be ignored.
* @return mixed Normalized value or input string
*/
public function normalize($value, $type)
{
// Integers and floats are validated first to prevent successful parsing
// of strings containing invalid characters with the invalid part simply
// cut off.
switch ($type) {
case 'integer':
$value = trim($value);
if (\Zend\Validator\StaticValidator::execute($value, 'Zend\\I18n\\Validator\\IsInt')) {
$value = \Zend\Filter\StaticFilter::execute($value, 'Zend\\I18n\\Filter\\NumberParse', array('type' => \NumberFormatter::TYPE_INT32));
}
break;
case 'float':
$value = trim($value);
if (\Zend\Validator\StaticValidator::execute($value, 'Zend\\I18n\\Validator\\IsFloat')) {
$value = \Zend\Filter\StaticFilter::execute($value, 'Zend\\I18n\\Filter\\NumberParse', array('type' => \NumberFormatter::TYPE_DOUBLE));
}
break;
case 'date':
$value = trim($value);
$validator = new \Zend\I18n\Validator\DateTime();
$validator->setDateType(\IntlDateFormatter::SHORT);
if ($validator->isValid($value)) {
// Some systems accept invalid date separators, like '/'
// with a de_DE locale which should accept only '.'.
// An extra comparision of the locale-specific pattern and
// the input string is necessary.
// This also enforces 4-digit years to avoid any confusion
// with 2-digit year input.
$pattern = preg_quote($validator->getPattern(), '#');
// Get the year part out of the way first.
$pattern = preg_replace('/y+/', '§', $pattern);
// Remaining letters are placeholders for digits.
$pattern = preg_replace('/[a-zA-Z]+/', '\\d+', $pattern);
// Set the year pattern.
$pattern = str_replace('§', '\\d{4}', $pattern);
if (preg_match("#^{$pattern}\$#", $value)) {
$formatter = new \IntlDateFormatter(\Locale::getDefault(), \IntlDateFormatter::SHORT, \IntlDateFormatter::NONE, 'UTC');
$value = \DateTime::createFromFormat('U', $formatter->parse($value));
}
}
break;
}
return $value;
}
示例4: parse_date
/**
* parses a date string into UNIX timestamp
*
* if "strict dates" is set, this function uses the DateTime or IntlDateFormatter
* class to parse the string according to a specific format. If it is not, we
* use the conventional strtotime() function, with the enhancement that if the
* non-American style format is used with slashes "d/m/Y" the string is prepared
* so strtotime can parse it correctly
*
* @param string $string the string to parse; if not given, defaults to now
* @param object $column_atts the column object; used to identify the field for
* user feedback
* @param bool $zero_time if set, zero the time portion of the date so it
* won't interfere with date comparisons
* @return int|bool UNIX timestamp or false if parse fails
*/
public static function parse_date($string = false, $column = '', $zero_time = false)
{
if (false === $string) {
return false;
}
$string = Participants_Db::set_filter('parse_date', $string, $column);
// is it already a timestamp?
if (self::is_valid_timestamp($string)) {
//if (WP_DEBUG and is_object($column)) error_log(__METHOD__.' tried to parse timestamp from '. $column->name);
return $string;
}
$date = false;
// if it is a default zero timestamp, treat it as "no date"
if ($string === '0000-00-00 00:00:00') {
return false;
}
/*
* we have two options to parse a date string into a timestamp: the
* IntlDateFormatter class or the DateTime class. The IntlDateFormatter
* class can parse localized text dates, but it seems commonly unavailable,
* at least on English-speaking servers. The DateTime class is widely
* available, but can't parse non-English text dates. It can parse numeric
* date representations, so if the intl module is not available, we try to
* use DateTime. If that is not available, we use strtotime with the added trick
* of swapping the date/month if they are slashes so slashed European notation
* can be correctly parsed
*/
self::$date_mode = 'none';
$errors = false;
$the_Date = false;
// test for MySQL-format timestamp
$is_MySQL_timestamp = preg_match('#^\\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2}:\\d{2}$#', $string) === 1 ? true : false;
//error_log(__METHOD__.' object? '.(is_object($column)?'yes':'no').' strict dates? '.(self::plugin_setting_is_true('strict_dates', false)?'yes':'no').' timestamp? '.($is_MySQL_timestamp?'yes':'no'));
if (self::plugin_setting_is_true('strict_dates', false) and is_object($column) and !$is_MySQL_timestamp) {
//error_log(__METHOD__.' intl? '.(class_exists('IntlDateFormatter')?'yes':'no').' datetime? '.(class_exists('DateTime')?'yes':'no'));
if (class_exists('IntlDateFormatter')) {
self::$date_mode = 'Intl';
$DateFormat = new IntlDateFormatter(get_locale(), IntlDateFormatter::LONG, IntlDateFormatter::NONE, NULL, NULL, Participants_Db::get_ICU_date_format(self::$plugin_options['input_date_format']));
$DateFormat->setLenient(false);
// we want it strict
$timestamp = $DateFormat->parse($string);
if ($DateFormat->getErrorCode() !== 0) {
$errors = array('code' => $DateFormat->getErrorCode(), 'error' => $DateFormat->getErrorMessage());
}
if (!$errors) {
$the_Date = new DateTime();
$the_Date->setTimestamp($timestamp);
} elseif (WP_DEBUG) {
error_log(__METHOD__ . ' IntlDateFormatter error: format string: ' . Participants_Db::get_ICU_date_format(self::$plugin_options['input_date_format']) . ' timestamp: ' . $timestamp . ' formatter error: ' . $DateFormat->getErrorMessage());
}
}
if (!$the_Date && class_exists('DateTime')) {
self::$date_mode = 'DateTime';
$the_Date = DateTime::createFromFormat(self::$plugin_options['input_date_format'], $string);
}
if (is_object($the_Date)) {
$errors = $the_Date->getLastErrors();
if ($errors['warning_count'] === 0 && $errors['error_count'] === 0) {
$errors = false;
}
}
if (is_array($errors) && !empty($string)) {
$the_Date = false;
if (is_object(self::$validation_errors) and is_object($column)) {
self::$validation_errors->add_error($column->name, sprintf(__('The date for "%s" was invalid. Please input the date with the exact format shown', 'participants-database'), $column->title));
}
if (WP_DEBUG) {
error_log(__METHOD__ . ' DateTime parse error: ' . implode(', ', $errors));
}
}
/*
* if we have a valid date, convert to timestamp
*/
if ($the_Date) {
/*
* zero the time so date equality comparisons can be made
*/
if ($zero_time) {
$the_Date->setTime(0, 0);
}
$date = $the_Date->format('U');
}
}
/*
//.........这里部分代码省略.........
示例5: date
/**
* {@inheritdoc}
* @SuppressWarnings(PHPMD.NPathComplexity)
*/
public function date($date = null, $locale = null, $useTimezone = true)
{
$locale = $locale ?: $this->_localeResolver->getLocale();
$timezone = $useTimezone ? $this->getConfigTimezone() : date_default_timezone_get();
if (empty($date)) {
return new \DateTime('now', new \DateTimeZone($timezone));
} elseif ($date instanceof \DateTime) {
return $date->setTimezone(new \DateTimeZone($timezone));
} elseif (!is_numeric($date)) {
$formatter = new \IntlDateFormatter($locale, \IntlDateFormatter::SHORT, \IntlDateFormatter::SHORT, new \DateTimeZone($timezone));
$date = $formatter->parse($date) ?: (new \DateTime($date))->getTimestamp();
}
return (new \DateTime(null, new \DateTimeZone($timezone)))->setTimestamp($date);
}
示例6: formatIntl
static function formatIntl($date)
{
$fmt = new IntlDateFormatter("pt_BR", IntlDateFormatter::FULL, IntlDateFormatter::FULL, 'America/Sao_Paulo', IntlDateFormatter::GREGORIAN, "d 'de' MMMM 'de' y");
return $fmt->parse($date);
}
示例7: parseDateByPattern
private function parseDateByPattern($formattedDate, $pattern)
{
$ftm = new IntlDateFormatter($this->locale, null, null, $this->timezoneName, null, $pattern);
return $ftm->parse($formattedDate);
}
示例8: _convertDate
/**
* Convert given date to default (UTC) timezone
*
* @param string $date
* @return \DateTime|null
*/
protected function _convertDate($date)
{
$timezone = $this->getColumn()->getTimezone() !== false ? $this->_localeDate->getConfigTimezone() : 'UTC';
$adminTimeZone = new \DateTimeZone($timezone);
$formatter = new \IntlDateFormatter($this->localeResolver->getLocale(), \IntlDateFormatter::SHORT, \IntlDateFormatter::NONE, $adminTimeZone);
$simpleRes = new \DateTime(null, $adminTimeZone);
$simpleRes->setTimestamp($formatter->parse($date));
$simpleRes->setTime(0, 0, 0);
$simpleRes->setTimezone(new \DateTimeZone('UTC'));
return $simpleRes;
}
示例9: _convertDate
/**
* Convert given date to default (UTC) timezone
*
* @param string $date
* @return \DateTime|null
*/
protected function _convertDate($date)
{
$adminTimeZone = new \DateTimeZone($this->_scopeConfig->getValue($this->_localeDate->getDefaultTimezonePath(), \Magento\Store\Model\ScopeInterface::SCOPE_STORE));
$formatter = new \IntlDateFormatter($this->localeResolver->getLocale(), \IntlDateFormatter::SHORT, \IntlDateFormatter::NONE, $adminTimeZone);
$simpleRes = new \DateTime(null, $adminTimeZone);
$simpleRes->setTimestamp($formatter->parse($date));
$simpleRes->setTime(0, 0, 0);
$simpleRes->setTimezone(new \DateTimeZone('UTC'));
return $simpleRes;
}
示例10: IntlDateFormatter
<?php
$fmt = new IntlDateFormatter("en_US", IntlDateFormatter::FULL, IntlDateFormatter::FULL);
var_dump($fmt->parse("Wednesday, January 20, 2038 3:14:07 AM GMT"));
示例11: IntlDateFormatter
<?php
$df = new IntlDateFormatter(Locale::getDefault(), 2, -1, "America/Los_Angeles", 1, "MM*yyyy*dd");
$df->setLenient(false);
$timestamp = $df->parse("06*2010*02");
var_dump($timestamp);
示例12: localeFormattedToUTCTimestamp
/**
* Locale Formatted datetime to UTC Timestamp
*
* @example Locale 22/10/15 14:17 to UTC Timestamp 1445516220 (2015-10-22 12:17:00)
*
* @param $datetime
* @param null $locale
* @return int|string
*/
public function localeFormattedToUTCTimestamp($datetime, $locale = null)
{
parent::setLocale($locale);
$dft = new IDF($this->locale, IDF::SHORT, IDF::SHORT, $this->timezone, IDF::GREGORIAN);
return $dft->parse($datetime);
}
示例13: parse_date
/**
* parses a date string into UNIX timestamp
*
* if "strict dates" is set, this function uses the DateTime or IntlDateFormatter
* class to parse the string according to a specific format. If it is not, we
* use the conventional strtotime() function, with the enhancement that if the
* non-American style format is used with slashes "d/m/Y" the string is prepared
* so strtotime can parse it correctly
*
* @param string $string the string to parse; if not given, defaults to now
* @param object $column_atts the column object; used to identify the field for
* user feedback
* @param bool $zero_time if set, zero the time portion of the date so it
* won't interfere with date comparisons
* @return int|bool UNIX timestamp or false if parse fails
*/
public static function parse_date($string = false, $column = '', $zero_time = false)
{
if (false === $string) {
return false;
}
$string = Participants_Db::set_filter('parse_date', $string, $column);
// it's already a timestamp
if (self::is_valid_timestamp($string)) {
//if (WP_DEBUG and is_object($column)) error_log(__METHOD__.' tried to parse timestamp from '. $column->name);
return $string;
}
$date = false;
// if it is a default zero timestamp or other empty value, treat it as "no date"
if ($string == '0000-00-00 00:00:00' || empty($string)) {
return false;
}
/*
* we have two options to parse a date string into a timestamp: the
* IntlDateFormatter class or the DateTime class. The IntlDateFormatter
* class can parse localized text dates, but it seems commonly unavailable,
* at least on English-speaking servers. The DateTime class is widely
* available, but can't parse non-English text dates. It can parse numeric
* date representations, so if the intl module is not available, we try to
* use DateTime. If that is not available, we use strtotime with the added trick
* of swapping out the separators if they are slashes so slashed European
* notation can be correctly parsed
*/
$mode = 'none';
$timestamp = is_object($column) && $column->form_element == 'timestamp' || preg_match('#^\\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2}:\\d{2}$#', $string) == 1 ? true : false;
if (self::$plugin_options['strict_dates'] == 1 and is_object($column) and !$timestamp) {
if (class_exists('IntlDateFormatter')) {
$mode = 'Intl';
$DateFormat = new IntlDateFormatter(WPLANG, IntlDateFormatter::LONG, IntlDateFormatter::NONE, NULL, NULL, Participants_Db::get_ICU_date_format(self::$date_format));
//error_log(__METHOD__.' format object:'.print_r($DateFormat,1));
$timestamp = $DateFormat->parse($string);
$the_Date = new DateTime();
$the_Date->setTimestamp($timestamp);
} else {
if (class_exists('DateTime')) {
$mode = 'DateTime';
$the_Date = DateTime::createFromFormat(self::$date_format, $string);
}
}
//error_log(__METHOD__.' date:'.print_r($the_Date,1));
if (is_array(date_get_last_errors()) && !empty($string)) {
$errors = date_get_last_errors();
if ($errors['warning_count'] > 0 || $errors['error_count'] > 0) {
$the_Date = false;
if (is_object(self::$validation_errors) and is_object($column)) {
self::$validation_errors->add_error($column->name, sprintf(__('The date for "%s" was invalid. Please input the date with the exact format shown', 'participants-database'), $column->title));
}
}
}
/*
* if we have a valid date, convert to timestamp
*/
if ($the_Date) {
/*
* zero the time so date equality comparisons can be made
*/
if ($zero_time) {
$the_Date->setTime(0, 0);
}
$date = $the_Date->format('U');
}
}
// ob_start();
// var_dump($date);
// error_log(__METHOD__.' date value:'.ob_get_clean().' mode:'.$mode);
/*
* if we haven't got a timestamp, parse the date the regular way
*/
if ($date === false or !self::is_valid_timestamp($date)) {
$mode = 'strtotime';
if (is_object($column) && $column->form_element == 'date') {
/*
* deal with the common special case of non-American-style numeric date with slashes
*/
if (false !== strpos($string, '/')) {
$date_parts = explode('/', self::$date_format);
$day_index = array_search('d', $date_parts) !== false ? array_search('d', $date_parts) : array_search('j', $date_parts);
$month_index = array_search('m', $date_parts) !== false ? array_search('m', $date_parts) : array_search('n', $date_parts);
if ($day_index !== false && $month_index !== false && $day_index < $month_index) {
$string = str_replace('/', '-', $string);
//.........这里部分代码省略.........
示例14: getDateTimeObjectFromLocaleDate
/**
* Get Date Time Object according to localized formated datetime
*
* @param string $date localized fromated date string
*
* @return \DateTime
*/
public static function getDateTimeObjectFromLocaleDate($date)
{
$formatter = new \IntlDateFormatter(\Locale::getDefault(), \IntlDateFormatter::MEDIUM, \IntlDateFormatter::NONE);
$dateTime = new \DateTime();
$dateTime->setTimestamp($formatter->parse($date));
return $dateTime;
}