/**
  * {@inheritdoc}
  */
 public function buildView(FormView $view, FormInterface $form, array $options)
 {
     $value = $form->getViewData();
     // set string representation
     if (true === $value) {
         $value = 'true';
     } elseif (false === $value) {
         $value = 'false';
     } elseif (null === $value) {
         $value = 'null';
     } elseif (is_array($value)) {
         $value = implode(', ', $value);
     } elseif ($value instanceof \DateTime) {
         $dateFormat = is_int($options['date_format']) ? $options['date_format'] : DateType::DEFAULT_FORMAT;
         $timeFormat = is_int($options['time_format']) ? $options['time_format'] : DateType::DEFAULT_FORMAT;
         $calendar = \IntlDateFormatter::GREGORIAN;
         $pattern = is_string($options['date_pattern']) ? $options['date_pattern'] : null;
         $formatter = new \IntlDateFormatter(\Locale::getDefault(), $dateFormat, $timeFormat, 'UTC', $calendar, $pattern);
         $formatter->setLenient(false);
         $value = $formatter->format($value);
     } elseif (is_object($value)) {
         if (method_exists($value, '__toString')) {
             $value = $value->__toString();
         } else {
             $value = get_class($value);
         }
     }
     $view->vars['value'] = (string) $value;
 }
 public function buildForm(FormBuilderInterface $builder, array $options)
 {
     $format = $options['format'];
     $pattern = null;
     $allowedFormatOptionValues = array(\IntlDateFormatter::FULL, \IntlDateFormatter::LONG, \IntlDateFormatter::MEDIUM, \IntlDateFormatter::SHORT);
     // If $format is not in the allowed options, it's considered as the pattern of the formatter if it is a string
     if (!in_array($format, $allowedFormatOptionValues, true)) {
         if (is_string($format)) {
             $format = self::DEFAULT_FORMAT;
             $pattern = $options['format'];
         } else {
             throw new CreationException('The "format" option must be one of the IntlDateFormatter constants (FULL, LONG, MEDIUM, SHORT) or a string representing a custom pattern');
         }
     }
     $formatter = new \IntlDateFormatter(\Locale::getDefault(), $format, \IntlDateFormatter::NONE, 'UTC', \IntlDateFormatter::GREGORIAN, $pattern);
     $formatter->setLenient(false);
     $builder->addViewTransformer(new DateTimeToLocalizedStringTransformer($options['data_timezone'], $options['user_timezone'], $format, \IntlDateFormatter::NONE, \IntlDateFormatter::GREGORIAN, $pattern));
     if ('string' === $options['input']) {
         $builder->addModelTransformer(new ReversedTransformer(new DateTimeToStringTransformer($options['data_timezone'], $options['data_timezone'], 'Y-m-d')));
     } elseif ('timestamp' === $options['input']) {
         $builder->addModelTransformer(new ReversedTransformer(new DateTimeToTimestampTransformer($options['data_timezone'], $options['data_timezone'])));
     } elseif ('array' === $options['input']) {
         $builder->addModelTransformer(new ReversedTransformer(new DateTimeToArrayTransformer($options['data_timezone'], $options['data_timezone'], array('year', 'month', 'day'))));
     }
     $builder->setAttribute('date_pattern', $formatter->getPattern());
 }
 /**
  * {@inheritdoc}
  */
 public function configureOptions(OptionsResolver $resolver)
 {
     $format = function (Options $options) {
         $date_format = \IntlDateFormatter::NONE;
         $time_format = \IntlDateFormatter::NONE;
         if ($options['date_picker']) {
             $date_format = \IntlDateFormatter::SHORT;
         }
         if ($options['time_picker']) {
             $time_format = $options['with_seconds'] ? \IntlDateFormatter::MEDIUM : \IntlDateFormatter::SHORT;
         }
         $formater = new \IntlDateFormatter($options['locale'], $date_format, $time_format, $options['user_timezone'], \IntlDateFormatter::GREGORIAN, null);
         $formater->setLenient(false);
         $pattern = $formater->getPattern();
         if (false === strpos($pattern, 'yyyy')) {
             if (false !== strpos($pattern, 'yy')) {
                 $pattern = str_replace('yy', 'yyyy', $pattern);
             } elseif (false !== strpos($pattern, 'y')) {
                 $pattern = str_replace('y', 'yyyy', $pattern);
             }
         }
         return $pattern;
     };
     $resolver->setDefaults(array('widget' => 'single_text', 'locale' => \Locale::getDefault(), 'user_timezone' => null, 'date_picker' => true, 'time_picker' => true, 'time_picker_first' => false, 'button_id' => null, 'open_focus' => true, 'hour_min' => null, 'hour_max' => null, 'hour_step' => null, 'minute_min' => null, 'minute_max' => null, 'minute_step' => null, 'second_min' => null, 'second_max' => null, 'second_step' => null, 'format' => $format, 'empty_value' => null, 'with_minutes' => true, 'with_seconds' => false));
 }
示例#4
0
 /**
  * {@inheritdoc}
  */
 public function format($value, array $options = [])
 {
     if (!$value instanceof \DateTimeInterface) {
         throw new InvalidTypeException(sprintf('The number formatter expects a numeric value, got "%s".', is_object($value) ? get_class($value) : gettype($value)));
     }
     $formatter = new \IntlDateFormatter($this->localeContext->getLocale(), isset($options['date_format']) ? $options['date_format'] : \IntlDateFormatter::MEDIUM, isset($options['time_format']) ? $options['time_format'] : \IntlDateFormatter::MEDIUM, isset($options['timezone']) ? $options['timezone'] : $value->getTimezone(), isset($options['calendar']) ? $options['calendar'] : null, isset($options['pattern']) ? $options['pattern'] : null);
     $formatter->setLenient(isset($options['lenient']) ? $options['lenient'] : false);
     return $formatter->format($value);
 }
示例#5
0
 /**
  * {@inheritdoc}
  */
 public function buildForm(FormBuilderInterface $builder, array $options)
 {
     $format = $options['format'];
     $pattern = null;
     $allowedFormats = array(\IntlDateFormatter::FULL, \IntlDateFormatter::LONG, \IntlDateFormatter::MEDIUM, \IntlDateFormatter::SHORT);
     // If $format is not in the allowed options, it's considered as the pattern of the formatter if it is a string
     if (!in_array($format, $allowedFormats, true)) {
         if (is_string($format)) {
             $format = self::DEFAULT_FORMAT;
             $pattern = $options['format'];
         } else {
             throw new CreationException('The "format" option must be one of the IntlDateFormatter constants (FULL, LONG, MEDIUM, SHORT) or a string representing a custom pattern');
         }
     }
     $formatter = new \IntlDateFormatter(\Locale::getDefault(), $format, \IntlDateFormatter::NONE, 'UTC', \IntlDateFormatter::GREGORIAN, $pattern);
     $formatter->setLenient(false);
     if ('single_text' === $options['widget']) {
         $builder->addViewTransformer(new DateTimeToLocalizedStringTransformer($options['data_timezone'], $options['user_timezone'], $format, \IntlDateFormatter::NONE, \IntlDateFormatter::GREGORIAN, $pattern));
     } else {
         $yearOptions = $monthOptions = $dayOptions = array();
         if ('choice' === $options['widget']) {
             if (is_array($options['empty_value'])) {
                 $options['empty_value'] = array_merge(array('year' => null, 'month' => null, 'day' => null), $options['empty_value']);
             } else {
                 $options['empty_value'] = array('year' => $options['empty_value'], 'month' => $options['empty_value'], 'day' => $options['empty_value']);
             }
             $years = $months = $days = array();
             foreach ($options['years'] as $year) {
                 $years[$year] = str_pad($year, 4, '0', STR_PAD_LEFT);
             }
             foreach ($options['months'] as $month) {
                 $months[$month] = str_pad($month, 2, '0', STR_PAD_LEFT);
             }
             foreach ($options['days'] as $day) {
                 $days[$day] = str_pad($day, 2, '0', STR_PAD_LEFT);
             }
             // Only pass a subset of the options to children
             $yearOptions = array('choices' => $years, 'empty_value' => $options['empty_value']['year']);
             $monthOptions = array('choices' => $this->formatMonths($formatter, $months), 'empty_value' => $options['empty_value']['month']);
             $dayOptions = array('choices' => $days, 'empty_value' => $options['empty_value']['day']);
             // Append generic carry-along options
             foreach (array('required', 'translation_domain') as $passOpt) {
                 $yearOptions[$passOpt] = $monthOptions[$passOpt] = $dayOptions[$passOpt] = $options[$passOpt];
             }
         }
         $builder->add('year', $options['widget'], $yearOptions)->add('month', $options['widget'], $monthOptions)->add('day', $options['widget'], $dayOptions)->addViewTransformer(new DateTimeToArrayTransformer($options['data_timezone'], $options['user_timezone'], array('year', 'month', 'day')));
     }
     if ('string' === $options['input']) {
         $builder->addModelTransformer(new ReversedTransformer(new DateTimeToStringTransformer($options['data_timezone'], $options['data_timezone'], 'Y-m-d')));
     } elseif ('timestamp' === $options['input']) {
         $builder->addModelTransformer(new ReversedTransformer(new DateTimeToTimestampTransformer($options['data_timezone'], $options['data_timezone'])));
     } elseif ('array' === $options['input']) {
         $builder->addModelTransformer(new ReversedTransformer(new DateTimeToArrayTransformer($options['data_timezone'], $options['data_timezone'], array('year', 'month', 'day'))));
     }
     $builder->setAttribute('formatter', $formatter);
 }
示例#6
0
 /**
  * {@inheritdoc}
  */
 public function buildForm(FormBuilderInterface $builder, array $options)
 {
     $dateFormat = is_int($options['format']) ? $options['format'] : self::DEFAULT_FORMAT;
     $timeFormat = \IntlDateFormatter::NONE;
     $calendar = \IntlDateFormatter::GREGORIAN;
     $pattern = is_string($options['format']) ? $options['format'] : null;
     if (!in_array($dateFormat, self::$acceptedFormats, true)) {
         throw new InvalidOptionsException('The "format" option must be one of the IntlDateFormatter constants (FULL, LONG, MEDIUM, SHORT) or a string representing a custom format.');
     }
     if (null !== $pattern && (false === strpos($pattern, 'y') || false === strpos($pattern, 'M') || false === strpos($pattern, 'd'))) {
         throw new InvalidOptionsException(sprintf('The "format" option should contain the letters "y", "M" and "d". Its current value is "%s".', $pattern));
     }
     if ('single_text' === $options['widget']) {
         $builder->addViewTransformer(new DateTimeToLocalizedStringTransformer($options['model_timezone'], $options['view_timezone'], $dateFormat, $timeFormat, $calendar, $pattern));
     } else {
         $yearOptions = $monthOptions = $dayOptions = array('error_bubbling' => true);
         $formatter = new \IntlDateFormatter(\Locale::getDefault(), $dateFormat, $timeFormat, null, $calendar, $pattern);
         // new \intlDateFormatter may return null instead of false in case of failure, see https://bugs.php.net/bug.php?id=66323
         if (!$formatter) {
             throw new InvalidOptionsException(intl_get_error_message(), intl_get_error_code());
         }
         $formatter->setLenient(false);
         if ('choice' === $options['widget']) {
             // Only pass a subset of the options to children
             $yearOptions['choices'] = $this->formatTimestamps($formatter, '/y+/', $this->listYears($options['years']));
             $yearOptions['choices_as_values'] = true;
             $yearOptions['placeholder'] = $options['placeholder']['year'];
             $yearOptions['choice_translation_domain'] = $options['choice_translation_domain']['year'];
             $monthOptions['choices'] = $this->formatTimestamps($formatter, '/[M|L]+/', $this->listMonths($options['months']));
             $monthOptions['choices_as_values'] = true;
             $monthOptions['placeholder'] = $options['placeholder']['month'];
             $monthOptions['choice_translation_domain'] = $options['choice_translation_domain']['month'];
             $dayOptions['choices'] = $this->formatTimestamps($formatter, '/d+/', $this->listDays($options['days']));
             $dayOptions['choices_as_values'] = true;
             $dayOptions['placeholder'] = $options['placeholder']['day'];
             $dayOptions['choice_translation_domain'] = $options['choice_translation_domain']['day'];
         }
         // Append generic carry-along options
         foreach (array('required', 'translation_domain') as $passOpt) {
             $yearOptions[$passOpt] = $monthOptions[$passOpt] = $dayOptions[$passOpt] = $options[$passOpt];
         }
         $builder->add('year', self::$widgets[$options['widget']], $yearOptions)->add('month', self::$widgets[$options['widget']], $monthOptions)->add('day', self::$widgets[$options['widget']], $dayOptions)->addViewTransformer(new DateTimeToArrayTransformer($options['model_timezone'], $options['view_timezone'], array('year', 'month', 'day')))->setAttribute('formatter', $formatter);
     }
     if ('string' === $options['input']) {
         $builder->addModelTransformer(new ReversedTransformer(new DateTimeToStringTransformer($options['model_timezone'], $options['model_timezone'], 'Y-m-d')));
     } elseif ('timestamp' === $options['input']) {
         $builder->addModelTransformer(new ReversedTransformer(new DateTimeToTimestampTransformer($options['model_timezone'], $options['model_timezone'])));
     } elseif ('array' === $options['input']) {
         $builder->addModelTransformer(new ReversedTransformer(new DateTimeToArrayTransformer($options['model_timezone'], $options['model_timezone'], array('year', 'month', 'day'))));
     }
 }
示例#7
0
 /**
  * @param $datetime
  * @param null $format
  * @return string
  */
 private function formatTimestamps($datetime, $format = null)
 {
     if (empty($datetime)) {
         return;
     }
     $dateFormat = is_int($format) ? $format : \IntlDateFormatter::MEDIUM;
     $timeFormat = \IntlDateFormatter::NONE;
     $calendar = \IntlDateFormatter::GREGORIAN;
     $pattern = is_string($format) ? $format : null;
     $formatter = new \IntlDateFormatter(\Locale::getDefault(), $dateFormat, $timeFormat, $datetime->getTimezone()->getName(), $calendar, $pattern);
     $formatter->setLenient(false);
     $timestamp = $datetime->getTimestamp();
     return $formatter->format($timestamp);
 }
 /**
  * {@inheritdoc}
  */
 public function buildView(FormView $view, FormInterface $form, array $options)
 {
     $configs = $options['configs'];
     $years = $options['years'];
     $configs['dateFormat'] = 'yy-mm-dd';
     if ('single_text' === $options['widget']) {
         $dateFormat = is_int($options['format']) ? $options['format'] : BaseDateType::DEFAULT_FORMAT;
         $timeFormat = \IntlDateFormatter::NONE;
         $calendar = \IntlDateFormatter::GREGORIAN;
         $pattern = is_string($options['format']) ? $options['format'] : null;
         $formatter = new \IntlDateFormatter(\Locale::getDefault(), $dateFormat, $timeFormat, 'UTC', $calendar, $pattern);
         $formatter->setLenient(false);
         $configs['dateFormat'] = $this->getJavascriptPattern($formatter);
     }
     $view->vars = array_replace($view->vars, array('min_year' => min($years), 'max_year' => max($years), 'configs' => $configs, 'culture' => $options['culture']));
 }
示例#9
0
 /**
  * {@inheritdoc}
  */
 public function buildForm(FormBuilder $builder, array $options)
 {
     $format = $options['format'];
     $pattern = null;
     $allowedFormatOptionValues = array(\IntlDateFormatter::FULL, \IntlDateFormatter::LONG, \IntlDateFormatter::MEDIUM, \IntlDateFormatter::SHORT);
     // If $format is not in the allowed options, it's considered as the pattern of the formatter if it is a string
     if (!in_array($format, $allowedFormatOptionValues, true)) {
         if (is_string($format)) {
             $defaultOptions = $this->getDefaultOptions($options);
             $format = $defaultOptions['format'];
             $pattern = $options['format'];
         } else {
             throw new CreationException('The "format" option must be one of the IntlDateFormatter constants (FULL, LONG, MEDIUM, SHORT) or a string representing a custom pattern');
         }
     }
     $formatter = new \IntlDateFormatter(\Locale::getDefault(), $format, \IntlDateFormatter::NONE, 'UTC', \IntlDateFormatter::GREGORIAN, $pattern);
     $formatter->setLenient(false);
     if ($options['widget'] === 'single_text') {
         $builder->appendClientTransformer(new DateTimeToLocalizedStringTransformer($options['data_timezone'], $options['user_timezone'], $format, \IntlDateFormatter::NONE, \IntlDateFormatter::GREGORIAN, $pattern));
     } else {
         $yearOptions = $monthOptions = $dayOptions = array();
         if ($options['widget'] === 'choice') {
             if (is_array($options['empty_value'])) {
                 $options['empty_value'] = array_merge(array('year' => null, 'month' => null, 'day' => null), $options['empty_value']);
             } else {
                 $options['empty_value'] = array('year' => $options['empty_value'], 'month' => $options['empty_value'], 'day' => $options['empty_value']);
             }
             // Only pass a subset of the options to children
             $yearOptions = array('choice_list' => new PaddedChoiceList(array_combine($options['years'], $options['years']), 4, '0', STR_PAD_LEFT), 'empty_value' => $options['empty_value']['year'], 'required' => $options['required']);
             $monthOptions = array('choice_list' => new MonthChoiceList($formatter, $options['months']), 'empty_value' => $options['empty_value']['month'], 'required' => $options['required']);
             $dayOptions = array('choice_list' => new PaddedChoiceList(array_combine($options['days'], $options['days']), 2, '0', STR_PAD_LEFT), 'empty_value' => $options['empty_value']['day'], 'required' => $options['required']);
         }
         $builder->add('year', $options['widget'], $yearOptions)->add('month', $options['widget'], $monthOptions)->add('day', $options['widget'], $dayOptions)->appendClientTransformer(new DateTimeToArrayTransformer($options['data_timezone'], $options['user_timezone'], array('year', 'month', 'day')));
     }
     if ($options['input'] === 'string') {
         $builder->appendNormTransformer(new ReversedTransformer(new DateTimeToStringTransformer($options['data_timezone'], $options['data_timezone'], 'Y-m-d')));
     } elseif ($options['input'] === 'timestamp') {
         $builder->appendNormTransformer(new ReversedTransformer(new DateTimeToTimestampTransformer($options['data_timezone'], $options['data_timezone'])));
     } elseif ($options['input'] === 'array') {
         $builder->appendNormTransformer(new ReversedTransformer(new DateTimeToArrayTransformer($options['data_timezone'], $options['data_timezone'], array('year', 'month', 'day'))));
     }
     $builder->setAttribute('formatter', $formatter)->setAttribute('widget', $options['widget']);
 }
示例#10
0
 /**
  * {@inheritdoc}
  */
 public function format($value, array $options = array())
 {
     if (null === $value) {
         return $options['null_value'];
     }
     if (!$value instanceof \DateTime) {
         throw FormatterException::invalidType($this, $value, 'DateTime instance');
     }
     $dateTime = clone $value;
     if ('UTC' !== $options['time_zone']) {
         $dateTime->setTimezone(new \DateTimeZone('UTC'));
     }
     $formatter = new \IntlDateFormatter(\Locale::getDefault(), $options['date_format'], $options['time_format'], $options['time_zone'], $options['calendar'], $options['pattern']);
     $formatter->setLenient(false);
     $value = $formatter->format((int) $dateTime->format('U'));
     if (intl_is_failure(intl_get_error_code())) {
         throw FormatterException::intlError($this, intl_get_error_message());
     }
     $value = preg_replace('~GMT\\+00:00$~', 'GMT', $value);
     return $value;
 }
示例#11
0
 /**
  * {@inheritdoc}
  */
 public function buildView(FormView $view, FormInterface $form, array $options)
 {
     $value = $form->getViewData();
     // set string representation
     if (true === $value) {
         $value = 'true';
     } elseif (false === $value) {
         $value = 'false';
     } elseif (null === $value) {
         $value = 'null';
     } elseif (is_array($value)) {
         $value = implode(', ', $value);
     } elseif ($value instanceof \DateTime) {
         $dateFormat = is_int($options['date_format']) ? $options['date_format'] : DateType::DEFAULT_FORMAT;
         $timeFormat = is_int($options['time_format']) ? $options['time_format'] : DateType::DEFAULT_FORMAT;
         $calendar = \IntlDateFormatter::GREGORIAN;
         $pattern = is_string($options['date_pattern']) ? $options['date_pattern'] : null;
         $formatter = new \IntlDateFormatter(\Locale::getDefault(), $dateFormat, $timeFormat, 'UTC', $calendar, $pattern);
         $formatter->setLenient(false);
         $value = $formatter->format($value);
     } elseif (is_object($value)) {
         /*      if (method_exists($value, '__toString')) {
                     $value = $value->__toString();
                 } else {
                     $value = get_class($value);
                 }*/
     }
     $view->vars['value'] = $value;
     $view->vars['value_type'] = '';
     if (is_object($value)) {
         $view->vars['value_class'] = get_class($value);
         if ($value instanceof Media && $this->container->has('sonata.media.twig.extension')) {
             $view->vars['media_helper'] = $this->container->get('sonata.media.twig.extension');
             $view->vars['value_type'] = 'media';
             $view->vars['media_format'] = $options['media_format'] ? $options['media_format'] : 'small';
         }
     }
 }
 /**
  * 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;
 }
 /**
  * Returns a preconfigured IntlDateFormatter instance
  *
  * @return \IntlDateFormatter
  */
 protected function getIntlDateFormatter()
 {
     $dateFormat = $this->dateFormat;
     $timeFormat = $this->timeFormat;
     $timezone = $this->outputTimezone;
     $calendar = $this->calendar;
     $pattern = $this->pattern;
     $intlDateFormatter = new \IntlDateFormatter(\Locale::getDefault(), $dateFormat, $timeFormat, $timezone, $calendar, $pattern);
     $intlDateFormatter->setLenient(false);
     return $intlDateFormatter;
 }
示例#14
0
 /**
  * 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');
         }
     }
     /*
      * if we haven't got a timestamp, parse the date the regular way
      */
     if ($date === false or !self::is_valid_timestamp($date)) {
         $date = false;
         // no valid date yet
         if (is_object($column) && $column->form_element == 'timestamp') {
             if ($zero_time) {
                 /*
                  * we need to zero the time, we first try to do it using the DateTime class
                  */
                 $the_Date = new DateTime($string);
                 if (is_object($the_Date)) {
                     $the_Date->setTime(0, 0);
                     $string = $the_Date->format(self::$date_format);
                 } else {
                     /*
                      * remove the time portion of the timestamp
                      */
                     $string = preg_replace('# [0-9]{2}:[0-9]{2}:[0-9]{2}$#', '', $string);
                     $string .= ' 00:00 -0';
                 }
             }
         }
         /*
          * @version 1.6
          * Most of the time, the default PHP timezone is the current setting, but 
          * experience has shown it's necessary to reset it for the conversion to make 
          * sure. We also must assume that the database server and PHP server are on 
          * the same TZ.
          */
         date_default_timezone_set(self::get_timezone());
         setlocale(LC_ALL, get_locale());
         /*
          * @version 1.6
          * added strptime method for locaized dates
          * 
          * this only works for known formats...so timestamps and when "strict dates" is enabled
          */
         if (function_exists('strptime') && (self::plugin_setting_is_true('strict_dates', false) || $is_MySQL_timestamp)) {
             self::$date_mode = 'strptime';
             if ($is_MySQL_timestamp) {
                 $format = '%Y-%m-%d';
             } else {
                 $format_setting = Participants_Db::plugin_setting_is_set('input_date_format') ? Participants_Db::plugin_setting('input_date_format') : get_bloginfo('date_format');
                 $format = Participants_Db::translate_date_format($format_setting, 'strftime');
             }
             $date_array = strptime($string, $format);
             $date = mktime($date_array['tm_hour'], $date_array['tm_min'], $date_array['tm_sec'], $date_array['tm_mon'] + 1, $date_array['tm_mday'], $date_array['tm_year'] + 1900);
         }
         if ($date === false) {
             self::$date_mode = 'strtotime';
             $date = strtotime(self::date_order_fix($string));
         }
     }
     return $date;
 }
<?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);
示例#16
0
 /**
  * @param $datetime
  * @param null $format
  * @return string
  */
 public function datefmtFormatFilter($datetime, $format = null)
 {
     $dateFormat = is_int($format) ? $format : \IntlDateFormatter::MEDIUM;
     $timeFormat = \IntlDateFormatter::NONE;
     $calendar = \IntlDateFormatter::GREGORIAN;
     $pattern = is_string($format) ? $format : null;
     $formatter = new \IntlDateFormatter(\Locale::getDefault(), $dateFormat, $timeFormat, date_default_timezone_get(), $calendar, $pattern);
     $formatter->setLenient(false);
     $timestamp = $datetime->getTimestamp();
     return $formatter->format($timestamp);
 }
示例#17
0
 /**
  * Converts view value to string
  * 
  * @param mixed $value
  * @param array $options
  * @return string
  */
 private function transform($value, array $options)
 {
     if (empty($value)) {
         $value = '-----';
     } elseif (is_array($value)) {
         $value = implode(', ', $value);
     } elseif ($value instanceof \DateTime) {
         $formatter = new \IntlDateFormatter($this->request->getLocale(), $options['date_format'], $options['time_format'], null, \IntlDateFormatter::GREGORIAN, $options['date_pattern']);
         $formatter->setLenient(false);
         $value = $formatter->format($value);
     } elseif (is_object($value)) {
         if (method_exists($value, '__toString')) {
             $value = $value->__toString();
         } else {
             $value = get_class($value);
         }
     }
     return (string) $value;
 }
 /**
  * Returns a preconfigured IntlDateFormatter instance.
  *
  * @param bool $ignoreTimezone Use UTC regardless of the configured timezone.
  *
  * @return \IntlDateFormatter
  *
  * @throws TransformationFailedException in case the date formatter can not be constructed.
  */
 protected function getIntlDateFormatter($ignoreTimezone = false)
 {
     $dateFormat = $this->dateFormat;
     $timeFormat = $this->timeFormat;
     $timezone = $ignoreTimezone ? 'UTC' : $this->outputTimezone;
     $calendar = $this->calendar;
     $pattern = $this->pattern;
     $intlDateFormatter = new \IntlDateFormatter(\Locale::getDefault(), $dateFormat, $timeFormat, $timezone, $calendar, $pattern);
     // new \intlDateFormatter may return null instead of false in case of failure, see https://bugs.php.net/bug.php?id=66323
     if (!$intlDateFormatter) {
         throw new TransformationFailedException(intl_get_error_message(), intl_get_error_code());
     }
     $intlDateFormatter->setLenient(false);
     return $intlDateFormatter;
 }
 protected function getIntlDateFormatter() : \IntlDateFormatter
 {
     $intlDateFormatter = new \IntlDateFormatter(\Locale::getDefault(), $this->dateFormat, $this->timeFormat, $this->outputTimezone, $this->calendar, $this->pattern);
     $intlDateFormatter->setLenient(false);
     // Ensure the year is always four digits when no pattern is set
     if ('' === $this->pattern) {
         $intlDateFormatter->setPattern(str_replace(['yy', 'yyyyyyyy'], 'yyyy', $intlDateFormatter->getPattern()));
     }
     return $intlDateFormatter;
 }