Example #1
0
 private function formatDateTimeValue($value, $format, $type)
 {
     $timeZone = $this->timeZone;
     // avoid time zone conversion for date-only values
     if ($type === 'date') {
         list($timestamp, $hasTimeInfo) = $this->normalizeDatetimeValue($value, true);
         if (!$hasTimeInfo) {
             $timeZone = $this->defaultTimeZone;
         }
     } else {
         $timestamp = $this->normalizeDatetimeValue($value);
     }
     if ($timestamp === null) {
         return $this->nullDisplay;
     }
     if (strncmp($format, 'php:', 4) === 0) {
         $format = substr($format, 4);
     } else {
         $format = FormatConverter::convertDateIcuToPhp($format, $type, $this->locale);
     }
     if ($timeZone != null) {
         if ($timestamp instanceof \DateTimeImmutable) {
             $timestamp = $timestamp->setTimezone(new \DateTimeZone($timeZone));
         } else {
             $timestamp->setTimezone(new \DateTimeZone($timeZone));
         }
     }
     return $this->dateTime->date($format, $timestamp->getTimestamp());
 }
 /**
  * @inheritdoc
  */
 public function init()
 {
     if ($this->logicalFormat === null) {
         $format = $this->type . 'Format';
         $pattern = Yii::$app->formatter->{$format};
     } else {
         $pattern = $this->logicalFormat;
     }
     if (substr($pattern, 0, 4) === 'php:') {
         $this->_phpLogicalFormat = substr($pattern, 4);
     } else {
         $this->_phpLogicalFormat = FormatConverter::convertDateIcuToPhp($pattern, $this->type);
     }
     if ($this->physicalFormat === null) {
         $driverName = Yii::$app->db->driverName;
         if (isset(static::$dbDatetimeFormat[$driverName])) {
             $pattern = static::$dbDatetimeFormat[$driverName][$this->type];
         } else {
             $pattern = static::$dbDatetimeFormat['default'][$this->type];
         }
     } else {
         $pattern = $this->physicalFormat;
     }
     if (substr($pattern, 0, 4) === 'php:') {
         $this->_phpPhysicalFormat = substr($pattern, 4);
     } else {
         $this->_phpPhysicalFormat = FormatConverter::convertDateIcuToPhp($pattern, $this->type);
     }
     parent::init();
 }
Example #3
0
 public function init()
 {
     parent::init();
     if (!$this->_localFormatPhp) {
         $this->_localFormatPhp = FormatConverter::convertDateIcuToPhp($this->localFormat[1], $this->localFormat[0]);
     }
 }
 public function run()
 {
     echo $this->renderWidget() . "\n";
     if (is_string($this->noConflict)) {
         /** @var AssetBundle $asset */
         $asset = $this->noConflict;
         $asset::register($this->view);
     }
     $asset = DatePickerAsset::register($this->view);
     $containerID = $this->options['id'];
     $language = $this->language ? $this->language : Yii::$app->language;
     $this->view->registerJsFile($asset->baseUrl . '/locales/bootstrap-datepicker.' . $language . '.min.js', ['depends' => ['yii\\web\\JqueryAsset', 'omnilight\\assets\\DatePickerAsset']]);
     if (strncmp($this->dateFormat, 'php:', 4) === 0) {
         $format = substr($this->dateFormat, 4);
     } else {
         $format = FormatConverter::convertDateIcuToPhp($this->dateFormat, 'datetime', $language);
     }
     $this->clientOptions['format'] = $this->convertDateFormat($format);
     $this->clientOptions['language'] = $language;
     if ($this->noConflict) {
         $this->registerNoConflict();
         $this->registerClientOptions('datepickerNoConflict', $containerID);
     } else {
         $this->registerClientOptions('datepicker', $containerID);
     }
 }
Example #5
0
 public function testIntlUtf8Ru()
 {
     $this->assertEquals('d M Y \\г.', FormatConverter::convertDateIcuToPhp('dd MMM y \'г\'.', 'date', 'ru-RU'));
     $this->assertEquals('dd M yy \'г\'.', FormatConverter::convertDateIcuToJui('dd MMM y \'г\'.', 'date', 'ru-RU'));
     $formatter = new Formatter(['locale' => 'ru-RU']);
     $this->assertEquals('24 авг 2014 г.', $formatter->asDate('2014-8-24', 'dd MMM y \'г\'.'));
 }
 /**
  * @param string $value
  */
 public function setValue($value)
 {
     $this->_value = $value;
     $normalizedFormat = DateTimeBehavior::normalizeIcuFormat($this->targetFormat, $this->behavior->formatter);
     $phpFormat = FormatConverter::convertDateIcuToPhp($normalizedFormat[1], $normalizedFormat[0], \Yii::$app->language);
     $dateTime = date_create_from_format($phpFormat, $value);
     $this->behavior->owner->{$this->originalAttribute} = $this->behavior->formatter->format($dateTime, $this->originalFormat);
 }
 /**
  * Converting the date format from PHP DateTime (or ICU format) to Moment.js DateTime format.
  * @param string $format the PHP date format string
  * @return string
  * @see http://php.net/manual/en/function.date.php
  * @see http://momentjs.com/docs/#/parsing/string-format/
  */
 protected function convertDateFormat($format)
 {
     if (strncmp($format, 'php:', 4) === 0) {
         $format = substr($format, 4);
     } else {
         $format = FormatConverter::convertDateIcuToPhp($format);
     }
     return strtr($format, ['s' => 'ss', 'i' => 'mm', 'g' => 'h', 'h' => 'hh', 'G' => 'H', 'H' => 'HH', 'w' => 'e', 'W' => 'E', 'j' => 'D', 'd' => 'DD', 'D' => 'DDD', 'l' => 'DDDD', 'n' => 'M', 'm' => 'MM', 'M' => 'MMM', 'F' => 'MMMM', 'y' => 'YY', 'Y' => 'YYYY', 'U' => 'X']);
 }
 public function init()
 {
     parent::init();
     if ($this->timeZoneConvert === null) {
         $this->timeZoneConvert = !($this->originalFormat != 'U' && $this->localFormat[0] == 'date');
     }
     if (!$this->_localFormatPhp) {
         $this->_localFormatPhp = FormatConverter::convertDateIcuToPhp($this->localFormat[1], $this->localFormat[0]);
     }
 }
Example #9
0
 /**
  * convert current yii date format to timestamp
  * @param string $date current date in Yii date format
  * @return bool|int
  */
 public static function date2timestamp($date)
 {
     $format = Yii::$app->formatter->dateFormat;
     if (strncmp($format, 'php:', 4) === 0) {
         $format = substr($format, 4);
     } else {
         $format = FormatConverter::convertDateIcuToPhp($format);
     }
     $d = DateTime::createFromFormat($format, $date);
     if ($d) {
         return $d->getTimestamp();
     }
     return false;
 }
 /**
  * @param Model $model
  * @param $attribute
  * @param array $options
  * @param string $datePickerClass
  * @return array
  */
 public static function get(Model $model, $attribute, $options = [], $datePickerClass = 'yii\\jui\\DatePicker')
 {
     try {
         $attribute = self::findAttribute($model, $attribute);
         $format = DateTimeBehavior::normalizeIcuFormat($attribute->targetFormat, $attribute->behavior->formatter);
         switch ($datePickerClass) {
             case 'yii\\jui\\DatePicker':
                 $defaults = ['language' => \Yii::$app->language, 'clientOptions' => ['dateFormat' => 'php:' . FormatConverter::convertDateIcuToJui($format[1], $format[0])]];
                 break;
             case 'omnilight\\widgets\\DatePicker':
                 $defaults = ['language' => \Yii::$app->language, 'dateFormat' => 'php:' . FormatConverter::convertDateIcuToPhp($format[1], $format[0])];
                 break;
             default:
                 return $options;
         }
     } catch (InvalidParamException $e) {
         $defaults = [];
     }
     return ArrayHelper::merge($defaults, $options);
 }
 /**
  * @param Model $model
  * @param string $attribute
  * @param array $options
  * @param string $datePickerClass
  * @return array
  */
 public static function get(Model $model, $attribute, $options = [], $datePickerClass = DateRangePicker::class)
 {
     $behavior = self::findBehavior($model, $attribute);
     $formatAttribute = null;
     try {
         $formatAttribute = self::findAttribute($model, $behavior->startAttribute);
         $formatAttribute = self::findAttribute($model, $behavior->endAttribute);
     } catch (InvalidParamException $e) {
     }
     $defaults = [];
     switch ($datePickerClass) {
         case DateRangePicker::class:
             $defaults = ['separator' => $behavior->separator];
             if ($formatAttribute) {
                 $format = DateTimeBehavior::normalizeIcuFormat($formatAttribute->targetFormat, $formatAttribute->behavior->formatter);
                 $defaults['dateFormat'] = 'php:' . FormatConverter::convertDateIcuToPhp($format[1], $format[0]);
             }
             break;
     }
     return ArrayHelper::merge($defaults, $options);
 }
 /**
  * Registers CKEditor JS
  */
 protected function registerClientScript()
 {
     $view = $this->getView();
     DateTimePickerAsset::register($view);
     if (!$this->jsFormat) {
         $this->jsFormat = DateTimePicker::convertPhpDateToMomentJs(FormatConverter::convertDateIcuToPhp($this->phpFormat));
     }
     /*
      * locale fix
      * @author <https://github.com/sim2github>
      */
     if (!isset($this->clientOptions['locale'])) {
         $applocale = strtolower(substr(Yii::$app->language, 0, 2));
         //First 2 letters
         $this->clientOptions['locale'] = $applocale;
     }
     if (!isset($this->clientOptions['format'])) {
         $this->clientOptions['format'] = $this->jsFormat;
     }
     if (!isset($this->clientOptions2['locale'])) {
         $applocale = strtolower(substr(Yii::$app->language, 0, 2));
         //First 2 letters
         $this->clientOptions2['locale'] = $applocale;
     }
     if (!isset($this->clientOptions2['format'])) {
         $this->clientOptions2['format'] = $this->jsFormat;
     }
     $config = empty($this->clientOptions) ? '' : Json::encode($this->clientOptions);
     $config2 = empty($this->clientOptions2) ? '' : Json::encode($this->clientOptions2);
     $js = "\$('#" . $this->options['id'] . "').datetimepicker({$config});";
     $js .= "\$('#" . $this->options2['id'] . "').datetimepicker({$config2});";
     $view->registerJs($js);
 }
Example #13
0
    /**
     * Parses date string into UNIX timestamp
     *
     * @param string $value string representing date
     * @return boolean|integer UNIX timestamp or false on failure
     */
    protected function parseDateValue($value)
    {
        if (is_array($value)) {
            return false;
        }
        $format = $this->format;
        if (strncmp($this->format, 'php:', 4) === 0) {
            $format = substr($format, 4);
        } else {
            if (extension_loaded('intl')) {
                if (isset($this->_dateFormats[$format])) {
                    $formatter = new IntlDateFormatter($this->locale, $this->_dateFormats[$format], IntlDateFormatter::NONE, $this->timeZone);
                } else {
                    $formatter = new IntlDateFormatter($this->locale, IntlDateFormatter::NONE, IntlDateFormatter::NONE, $this->timeZone, null, $format);
                }
                // enable strict parsing to avoid getting invalid date values
                $formatter->setLenient(false);

                // There should not be a warning thrown by parse() but this seems to be the case on windows so we suppress it here
                // See https://github.com/yiisoft/yii2/issues/5962 and https://bugs.php.net/bug.php?id=68528
                $parsePos = 0;
                $parsedDate = @$formatter->parse($value, $parsePos);
                if ($parsedDate !== false && $parsePos === mb_strlen($value, Yii::$app ? Yii::$app->charset : 'UTF-8')) {
                    return $parsedDate;
                }
                return false;
            } else {
                // fallback to PHP if intl is not installed
                $format = FormatConverter::convertDateIcuToPhp($format, 'date');
            }
        }
        $date = DateTime::createFromFormat($format, $value, new \DateTimeZone($this->timeZone));
        $errors = DateTime::getLastErrors();
        if ($date === false || $errors['error_count'] || $errors['warning_count']) {
            return false;
        } else {
            // if no time was provided in the format string set time to 0 to get a simple date timestamp
            if (strpbrk($format, 'HhGgis') === false) {
                $date->setTime(0, 0, 0);
            }
            return $date->getTimestamp();
        }
    }
Example #14
0
 /**
  * @param $value array - a fuzzy date in array form (having keys 'y', 'm', and 'd').
  * @param null $format - see $fuzzyDateFormat; if null $fuzzyDateFormat is used
  * @return string - the formatted fuzzy date
  * @throws NotSupportedException
  */
 public function asFuzzyDate($value, $format = null)
 {
     $_dateFormats = ['short' => IntlDateFormatter::SHORT, 'medium' => IntlDateFormatter::MEDIUM, 'long' => IntlDateFormatter::LONG, 'full' => IntlDateFormatter::FULL];
     if ($value === null) {
         return $this->nullDisplay;
     }
     if (!is_array($value)) {
         throw new InvalidParamException('Formatting fuzzy date failed.');
     }
     if (!extension_loaded('intl')) {
         // can't use $this->_intlLoaded (private)
         throw new NotSupportedException('Extension \'Intl\' not loaded');
     }
     if (!$format) {
         $format = $this->fuzzyDateFormat;
     }
     $granularity = 'full';
     if (!isset($value['d']) || empty($value['d'])) {
         $granularity = isset($value['m']) && !empty($value['m']) ? 'month' : 'year';
     }
     $dt = new DateTime();
     $tokens = null;
     switch ($granularity) {
         case 'month':
             $dt->setDate($value['y'], $value['m'], 1);
             $tokens = 'cDdEeFWw';
             // ICU-tokens having to do with day
             break;
         case 'year':
             $dt->setDate($value['y'], 1, 1);
             $tokens = 'cDdEeFLMWw';
             // ICU-tokens having to do with day or month
             break;
         default:
             // 'full', finest granularity, use full pattern
             $dt->setDate($value['y'], $value['m'], $value['d']);
             break;
     }
     $formatter = null;
     if (is_array($format)) {
         $pattern = $format[$granularity];
     } else {
         if (isset($_dateFormats[$format])) {
             $formatter = new IntlDateFormatter($this->locale, $_dateFormats[$format], IntlDateFormatter::NONE);
             $format = $formatter->getPattern();
         } else {
             if (strncmp($format, 'php:', 4) === 0) {
                 $format = FormatConverter::convertDatePhpToIcu(substr($format, 4));
             }
         }
         if ($tokens) {
             // use PCRE_UTF8 modifier ('u') for regular expressions
             $pattern = preg_replace("/'[^']+'\\s?[{$tokens}]+\\S?\\s?|(?:('[^']+')|[{$tokens}]+\\S?\\s?)/u", '$1', $format);
             // remove tokens, possibly
             // with prepended quoted string, possibly with appended non-space and space, unless in single quoted string
             $pattern = preg_replace('/^(\'[^\']*\'\\s*)+|(\\s*\'[^\']*\')+$|\\W$/u', '', $pattern);
             // remove (possibly multiple) quoted strings at begin or end, non-word character from end
         } else {
             $pattern = $format;
         }
     }
     if (!$formatter) {
         $formatter = new IntlDateFormatter($this->locale, IntlDateFormatter::NONE, IntlDateFormatter::NONE);
     }
     // New in 1.0.1 : fall back to PHP if 32 bits and 'extreme' date
     if (PHP_INT_SIZE > 4 || $value['y'] > 1901 && $value['y'] < 2038) {
         $formatter->setPattern($pattern);
         return $formatter->format($dt);
     } else {
         return $dt->format(FormatConverter::convertDateIcuToPhp($pattern));
     }
 }
Example #15
0
 /**
  * @param array           $field
  * @param \yii\base\Model $model
  *
  * @return array поля для обновления в БД
  */
 public static function onLoad($field, $model)
 {
     $fieldName = $field[\cs\base\BaseForm::POS_DB_NAME];
     $array = Yii::$app->request->post($model->formName());
     $value = ArrayHelper::getValue($array, $fieldName, '');
     if ($value == '') {
         $model->{$fieldName} = null;
     } else {
         $dateFormat = ArrayHelper::getValue($field, 'widget.1.dateFormat', 'php:d.m.Y');
         if (strncmp($dateFormat, 'php:', 4) === 0) {
             $dateFormat = substr($dateFormat, 4);
         } else {
             $dateFormat = FormatConverter::convertDateIcuToPhp($dateFormat);
         }
         $model->{$fieldName} = \DateTime::createFromFormat($dateFormat, $value);
     }
 }
Example #16
0
 /**
  * Parse and return format understood by PHP DateTime
  */
 public static function parseFormat($format, $type)
 {
     if (strncmp($format, 'php:', 4) === 0) {
         return substr($format, 4);
     } elseif ($format != '') {
         return FormatConverter::convertDateIcuToPhp($format, $type);
     } else {
        throw InvalidConfigException("Error parsing '{$type}' format.");
     }
 }
Example #17
0
 /**
  * @param integer|string|DateTime $value the value to be formatted. The following
  * types of value are supported:
  *
  * - an integer representing a UNIX timestamp
  * - a string that can be [parsed to create a DateTime object](http://php.net/manual/en/datetime.formats.php).
  *   The timestamp is assumed to be in UTC unless a timezone is explicitly given.
  * - a PHP [DateTime](http://php.net/manual/en/class.datetime.php) object
  *
  * @param string $format the format used to convert the value into a date string.
  * @param string $type 'date', 'time', or 'datetime'.
  * @throws InvalidConfigException if the date format is invalid.
  * @return string the formatted result.
  */
 private function formatDateTimeValue($value, $format, $type)
 {
     $timestamp = $this->normalizeDatetimeValue($value);
     if ($timestamp === null) {
         return $this->nullDisplay;
     }
     if ($this->_intlLoaded) {
         if (strncmp($format, 'php:', 4) === 0) {
             $format = FormatConverter::convertDatePhpToIcu(substr($format, 4));
         }
         if (isset($this->_dateFormats[$format])) {
             if ($type === 'date') {
                 $formatter = new IntlDateFormatter($this->locale, $this->_dateFormats[$format], IntlDateFormatter::NONE, $this->timeZone);
             } elseif ($type === 'time') {
                 $formatter = new IntlDateFormatter($this->locale, IntlDateFormatter::NONE, $this->_dateFormats[$format], $this->timeZone);
             } else {
                 $formatter = new IntlDateFormatter($this->locale, $this->_dateFormats[$format], $this->_dateFormats[$format], $this->timeZone);
             }
         } else {
             $formatter = new IntlDateFormatter($this->locale, IntlDateFormatter::NONE, IntlDateFormatter::NONE, $this->timeZone, null, $format);
         }
         if ($formatter === null) {
             throw new InvalidConfigException(intl_get_error_message());
         }
         return $formatter->format($timestamp);
     } else {
         if (strncmp($format, 'php:', 4) === 0) {
             $format = substr($format, 4);
         } else {
             $format = FormatConverter::convertDateIcuToPhp($format, $type, $this->locale);
         }
         if ($this->timeZone != null) {
             $timestamp->setTimezone(new DateTimeZone($this->timeZone));
         }
         return $timestamp->format($format);
     }
 }
Example #18
0
 /**
  * Get timestamp as integer or date time object or as a specific format
  *
  * @param string      $source the timestamp string
  * @param bool|string $format
  * - if set to `true` will return as PHP DateTime object
  * - if set to `false` will return as integer
  * - if string - will be treated as the format
  *
  * @return integer
  */
 public function timestamp($source, $format = true)
 {
     $fmtSource = !empty($this->datetimeSaveFormat) ? $this->datetimeSaveFormat : 'php:U';
     $fmtSource = strncmp($fmtSource, 'php:', 4) === 0 ? substr($fmtSource, 4) : FormatConverter::convertDateIcuToPhp($fmtSource, 'datetime');
     try {
         $timestamp = DateTime::createFromFormat($fmtSource, $source);
     } catch (\Exception $e) {
         return null;
     }
     return $format === true ? $timestamp : ($format === false ? date_format($timestamp, 'U') : date_format($timestamp, $format));
 }
 private function formatDateTimeValue($value, $format, $type)
 {
     $timeZone = $this->timeZone;
     // avoid time zone conversion for date-only values
     if ($type === 'date') {
         list($timestamp, $hasTimeInfo) = $this->normalizeDatetimeValue($value, true);
         if (!$hasTimeInfo) {
             $timeZone = $this->defaultTimeZone;
         }
     } else {
         $timestamp = $this->normalizeDatetimeValue($value);
     }
     if ($timestamp === null) {
         return $this->nullDisplay;
     }
     // intl does not work with dates >=2038 or <=1901 on 32bit machines, fall back to PHP
     $year = $timestamp->format('Y');
     if ($this->_intlLoaded && !(PHP_INT_SIZE == 4 && ($year <= 1901 || $year >= 2038))) {
         if (strncmp($format, 'php:', 4) === 0) {
             $format = FormatConverter::convertDatePhpToIcu(substr($format, 4));
         }
         if (isset($this->_dateFormats[$format])) {
             if ($type === 'date') {
                 $formatter = new IntlDateFormatter($this->locale, $this->_dateFormats[$format], IntlDateFormatter::NONE, $timeZone);
             } elseif ($type === 'time') {
                 $formatter = new IntlDateFormatter($this->locale, IntlDateFormatter::NONE, $this->_dateFormats[$format], $timeZone);
             } else {
                 $formatter = new IntlDateFormatter($this->locale, $this->_dateFormats[$format], $this->_dateFormats[$format], $timeZone);
             }
         } else {
             $formatter = new IntlDateFormatter($this->locale, IntlDateFormatter::NONE, IntlDateFormatter::NONE, $timeZone, null, $format);
         }
         if ($formatter === null) {
             throw new InvalidConfigException(intl_get_error_message());
         }
         // make IntlDateFormatter work with DateTimeImmutable
         if ($timestamp instanceof \DateTimeImmutable) {
             $timestamp = new DateTime($timestamp->format(DateTime::ISO8601), $timestamp->getTimezone());
         }
         return $formatter->format($timestamp);
     } else {
         if (strncmp($format, 'php:', 4) === 0) {
             $format = substr($format, 4);
         } else {
             $format = FormatConverter::convertDateIcuToPhp($format, $type, $this->locale);
         }
         if ($timeZone != null) {
             if ($timestamp instanceof \DateTimeImmutable) {
                 $timestamp = $timestamp->setTimezone(new DateTimeZone($timeZone));
             } else {
                 $timestamp->setTimezone(new DateTimeZone($timeZone));
             }
         }
         return $timestamp->format($format);
     }
 }
Example #20
0
 protected function back($value)
 {
     $format = '!' . FormatConverter::convertDateIcuToPhp(Yii::$app->formatter->dateFormat);
     return DateTime::createFromFormat($format, $value)->format('Y-m-d');
 }
Example #21
0
 protected function parseDateValue($value)
 {
     if (is_array($value)) {
         return false;
     }
     $format = $this->format;
     if (strncmp($this->format, 'php:', 4) === 0) {
         $format = substr($format, 4);
     } else {
         if (extension_loaded('intl')) {
             if (isset($this->_dateFormats[$format])) {
                 $formatter = new IntlDateFormatter($this->locale, $this->_dateFormats[$format], IntlDateFormatter::NONE, $this->timeZone);
             } else {
                 $formatter = new IntlDateFormatter($this->locale, IntlDateFormatter::NONE, IntlDateFormatter::NONE, $this->timeZone, null, $format);
             }
             // enable strict parsing to avoid getting invalid date values
             $formatter->setLenient(false);
             return $formatter->parse($value);
         } else {
             // fallback to PHP if intl is not installed
             $format = FormatConverter::convertDateIcuToPhp($format, 'date');
         }
     }
     $date = DateTime::createFromFormat($format, $value, new \DateTimeZone($this->timeZone));
     $errors = DateTime::getLastErrors();
     if ($date === false || $errors['error_count'] || $errors['warning_count']) {
         return false;
     } else {
         // if no time was provided in the format string set time to 0 to get a simple date timestamp
         if (strpbrk($format, 'HhGgis') === false) {
             $date->setTime(0, 0, 0);
         }
         return $date->getTimestamp();
     }
 }
 /**
  * Parses date string into UNIX timestamp
  *
  * @param string $value string representing date
  * @return integer|false a UNIX timestamp or `false` on failure.
  */
 protected function parseDateValue($value)
 {
     if (is_array($value)) {
         return false;
     }
     $format = $this->format;
     if (strncmp($this->format, 'php:', 4) === 0) {
         $format = substr($format, 4);
     } else {
         if (extension_loaded('intl')) {
             return $this->parseDateValueIntl($value, $format);
         } else {
             // fallback to PHP if intl is not installed
             $format = FormatConverter::convertDateIcuToPhp($format, 'date');
         }
     }
     return $this->parseDateValuePHP($value, $format);
 }
Example #23
0
 public function testIntlIcuToPhpShortForm()
 {
     $this->assertEquals('n/j/y', FormatConverter::convertDateIcuToPhp('short', 'date', 'en-US'));
     $this->assertEquals('d.m.y', FormatConverter::convertDateIcuToPhp('short', 'date', 'de-DE'));
 }
 /**
  * Registers CKEditor JS
  */
 protected function registerClientScript()
 {
     $view = $this->getView();
     DateTimePickerAsset::register($view);
     /*
      * Language fix
      * @author <https://github.com/sim2github>
      */
     if (!isset($this->clientOptions['locale'])) {
         $appLanguage = strtolower(substr(Yii::$app->language, 0, 2));
         //First 2 letters
         $this->clientOptions['locale'] = $appLanguage;
     }
     if (!$this->jsFormat) {
         $this->jsFormat = static::convertPhpDateToMomentJs(FormatConverter::convertDateIcuToPhp($this->phpFormat));
     }
     if (!isset($this->clientOptions['format'])) {
         $this->clientOptions['format'] = $this->jsFormat;
     }
     if (!isset($this->clientOptions['minDate'])) {
         $this->clientOptions['minDate'] = '1900-01-01';
     }
     if (!isset($this->clientOptions['widgetPositioning'])) {
         $this->clientOptions['widgetPositioning'] = ['horizontal' => $this->addonBefore ? 'left' : 'right', 'vertical' => 'auto'];
     }
     $config = empty($this->clientOptions) ? '' : Json::encode($this->clientOptions);
     $js[] = "\$('" . $this->selector . "').datetimepicker({$config})";
     foreach ($this->clientEvents as $key => $value) {
         $js[] = ".on('{$key}', {$value})";
     }
     $js[] = ";\n";
     $view->registerJs(implode('', $js));
 }
Example #25
0
 /**
  * Formats a timestamp using the specified format
  * @param integer $timestamp
  * @param string $format
  * @return string
  */
 private function formatTimestamp($timestamp, $format)
 {
     if (strncmp($format, 'php:', 4) === 0) {
         $format = substr($format, 4);
     } else {
         $format = FormatConverter::convertDateIcuToPhp($format, 'date');
     }
     $date = new DateTime();
     $date->setTimestamp($timestamp);
     $date->setTimezone(new \DateTimeZone($this->timestampAttributeTimeZone));
     return $date->format($format);
 }
 /**
  * Parses a date value into a UNIX-Timestamp
  * 
  * @param string $value string representing date
  * @param string $format the expected date format
  * @param string $locale string the locale ID that is used to localize the date parsing.
  * This is only effective when the [PHP intl extension](http://php.net/manual/en/book.intl.php) is installed.
  * If not set, the locale of the [[\yii\base\Application::formatter|formatter]] will be used.
  * See also [[\yii\i18n\Formatter::locale]].
  * @param string $timeZone the timezone to use for parsing date and time values.
  * This can be any value that may be passed to [date_default_timezone_set()](http://www.php.net/manual/en/function.date-default-timezone-set.php)
  * e.g. `UTC`, `Europe/Berlin` or `America/Chicago`.
  * Refer to the [php manual](http://www.php.net/manual/en/timezones.php) for available timezones.
  * If this property is not set, [[\yii\base\Application::timeZone]] will be used.
  * @return integer|boolean a UNIX timestamp or `false` on failure.
  */
 public static function parseFromDate($value, $format, $locale = null, $timeZone = 'UTC')
 {
     //default values
     $locale = $locale === null ? Yii::$app->language : $locale;
     //decide which parser to use
     if (strncmp($format, 'php:', 4) === 0) {
         $format = substr($format, 4);
     } else {
         if (ServerConfig::extIntlLoaded()) {
             return static::parseDateValueIntl($value, $format, $locale, $timeZone);
         } else {
             $format = FormatConverter::convertDateIcuToPhp($format, 'date');
         }
     }
     return static::parseDateValuePHP($value, $format, $timeZone);
 }
Example #27
0
 /**
  * Parses date format based on attribute type using yii\helpers\FormatConverter
  * Used only within DatePicker and DateTimePicker.
  *
  * @param string $type the attribute type whether date, datetime, or time
  *
  * @return mixed|string
  * @throws InvalidConfigException
  */
 protected function parseDateFormat($type)
 {
     if (!$this->convertFormat) {
         return;
     }
     if (isset($this->pluginOptions['format'])) {
         $format = $this->pluginOptions['format'];
         $format = strncmp($format, 'php:', 4) === 0 ? substr($format, 4) : FormatConverter::convertDateIcuToPhp($format, $type);
         $this->pluginOptions['format'] = static::convertDateFormat($format);
         return;
     }
     $attrib = $type . 'Format';
     $format = isset(Yii::$app->formatter->{$attrib}) ? Yii::$app->formatter->{$attrib} : '';
     if (isset($this->dateFormat) && strncmp($this->dateFormat, 'php:', 4) === 0) {
         $this->pluginOptions['format'] = static::convertDateFormat(substr($format, 4));
     } elseif ($format != '') {
         $format = FormatConverter::convertDateIcuToPhp($format, $type);
         $this->pluginOptions['format'] = static::convertDateFormat($format);
     } else {
         throw InvalidConfigException("Error parsing '{$type}' format.");
     }
 }
 public function testEscapedIcuToJui()
 {
     $this->assertEquals('l, F j, Y \\a\\t g:i:s a T', FormatConverter::convertDateIcuToPhp('EEEE, MMMM d, y \'at\' h:mm:ss a zzzz'));
     $this->assertEquals('\'o\'\'clock\'', FormatConverter::convertDateIcuToJui('\'o\'\'clock\''));
 }
 protected function localize()
 {
     if (strncmp($this->dateFormat, 'php:', 4) === 0) {
         $format = $this->convertDateFormat(substr($this->dateFormat, 4));
     } elseif (strncmp($this->dateFormat, 'moment:', 7) === 0) {
         $format = Json::encode(substr($this->dateFormat, 7));
         $format = new JsExpression("moment.localeData().longDateFormat(" . $format . ")");
     } else {
         $format = $this->convertDateFormat(FormatConverter::convertDateIcuToPhp($this->dateFormat, 'datetime', $this->language));
     }
     $this->clientOptions['locale'] = ['format' => $format, 'applyLabel' => Yii::t('omnilight/daterangepicker', 'Apply', [], $this->language), 'cancelLabel' => Yii::t('omnilight/daterangepicker', 'Cancel', [], $this->language), 'fromLabel' => Yii::t('omnilight/daterangepicker', 'From', [], $this->language), 'toLabel' => Yii::t('omnilight/daterangepicker', 'To', [], $this->language), 'weekLabel' => Yii::t('omnilight/daterangepicker', 'W', [], $this->language), 'customRangeLabel' => Yii::t('omnilight/daterangepicker', 'Custom Range', [], $this->language)];
 }
Example #30
0
 /**
  * @param string $value    the value to be filtered
  * @param string $format   the format the date should be in
  * @param string $dbFormat the format to convert to
  * @param bool $adjustTimezone
  * @return string the formatted result.
  */
 private function filterDateTimeValue($value, $format, $dbFormat, $adjustTimezone = true)
 {
     if ($value === null) {
         return null;
     }
     $timeZone = new \DateTimeZone($adjustTimezone ? $this->timeZone : $this->dbTimeZone);
     if (strncmp($format, 'php:', 4) === 0) {
         $format = substr($format, 4);
     } else {
         $format = FormatConverter::convertDateIcuToPhp($format, 'datetime', $this->locale);
     }
     try {
         $date = \DateTime::createFromFormat($format, $value, $timeZone);
     } catch (\Exception $e) {
         return $value;
     }
     if ($date === false) {
         return $value;
     }
     if ($adjustTimezone) {
         $date->setTimezone(new \DateTimeZone($this->dbTimeZone));
         $date->setTime(0, 0, 0);
     }
     return $date->format($dbFormat);
 }