/** * @param string|\DateTimeInterface $date * * @return string */ public function getDateFormatted($date) : string { if ($date instanceof \DateTimeInterface) { return $this->formatter->format($date->getTimestamp()); } elseif (is_string($date)) { return $this->formatter->format(strtotime($date)); } else { return ''; } }
/** * @param string $name * @param \IntlDateFormatter $formatter * * @return \Twig_SimpleFilter */ private function getIntlDateFilter($name, \IntlDateFormatter $formatter) { return new \Twig_SimpleFilter($name, function ($dateValue) use($formatter) { if ($dateValue instanceof \DateTimeInterface) { return $formatter->format($dateValue->getTimestamp()); } elseif (is_string($dateValue)) { return $formatter->format($dateValue); } else { return ''; } }); }
public function buildForm(FormBuilderInterface $builder, array $options) { // Create the sample date and time data to be displayed // in the select form fields $now = new \DateTime(); // Set user's timezone //$now->setTimezone(new \DateTimeZone($options['data']->getTimezone())); // Format output according to user's locale $localeFormat = new \IntlDateFormatter($options['data']->getLocale(), \IntlDateFormatter::FULL, \IntlDateFormatter::FULL, (new \DateTimeZone($options['data']->getTimezone()))->getName()); if (is_array($this->formats['date']) && count($this->formats['date']) && is_array($this->formats['time']) && count($this->formats['time'])) { foreach ($this->formats['date'] as $dateFormat) { // Display format with current date to user $localeFormat->setPattern($dateFormat); $dateFormats[$dateFormat] = $localeFormat->format($now); } foreach ($this->formats['time'] as $timeFormat) { // Display format with current date to user $localeFormat->setPattern($timeFormat); $timeFormats[$timeFormat] = $localeFormat->format($now); } } $builder->add('username', 'text', array('constraints' => array(new Assert\NotBlank())))->add('email', 'email', array('constraints' => array(new Assert\NotBlank(), new Assert\Email())))->add('firstName', 'text', array('constraints' => array(new Assert\NotBlank())))->add('lastName', 'text', array('constraints' => array(new Assert\NotBlank())))->add('timezone', 'timezone')->add('avatarImage', new AvatarUploadType(), array('label' => 'Profile image')); if ($options['new']) { $builder->add('password', 'repeated', array('required' => true, 'type' => 'password', 'first_name' => 'password', 'second_name' => 'password_again', 'invalid_message' => 'The password fields must match.')); } // $builder // ->add('language', 'language', array( // 'data' => 'en_US', // 'disabled' => true // )) // ->add('locale', 'locale', array( // 'data' => 'en_US', // 'disabled' => true, // )) // ->add('currency', 'currency', array( // 'data' => 'USD', // 'disabled' => true // )) // ->add('dateFormat', 'choice', array( // 'data' => 'yyyy-MM-dd', // 'disabled' => true, // 'label' => 'Date Format', // 'choices' => $dateFormats, // 'multiple' => false, // )) // ->add('timeFormat', 'choice', array( // 'data' => 'HH:mm:ss', // 'disabled' => true, // 'label' => 'Time Format', // 'choices' => $timeFormats, // 'multiple' => false, // )); }
public function query($departure, $arrival, \DateTime $date = null) { $date = $date ? $date : new \DateTime(); $fmt = new \IntlDateFormatter('en_EN', \IntlDateFormatter::FULL, \IntlDateFormatter::NONE, date_default_timezone_get(), \IntlDateFormatter::TRADITIONAL); $response = $this->client->post('bin/query.exe/fn', array('headers' => array('host' => 'fahrplan.sbb.ch', 'origin' => 'http://fahrplan.sbb.ch', 'referer' => 'http://fahrplan.sbb.ch/bin/query.exe/fn'), 'form_params' => array('queryPageDisplayed' => 'yes', 'HWAI=JS!ajax' => 'yes', 'HWAI=JS!js' => 'yes', 'HWAI' => '~CONNECTION!', 'REQ0Total_KissRideMotorClass' => '404', 'REQ0Total_KissRideCarClass' => '5', 'REQ0Total_KissRide_maxDist' => '10000000', 'REQ0Total_KissRide_minDist' => '0', 'REQComparisonCarload' => '0', 'REQ0JourneyStopsS0G' => $departure['value'], 'REQ0JourneyStopsS0ID' => $departure['id'], 'REQ0JourneyStopsS0A' => '255', 'REQ0JourneyStopsZ0G' => $arrival['value'], 'REQ0JourneyStopsZ0ID' => $arrival['id'], 'REQ0JourneyStopsZ0A' => '255', 'REQ0JourneyStops1.0G' => '', 'REQ0JourneyStops1.0A' => '1', 'REQ0JourneyStopover1' => '', 'date' => sprintf('%s, %s', substr($fmt->format($date), 0, 2), $date->format('d-m-y')), 'REQ0JourneyTime' => $date->format('H:i'), 'REQ0HafasSearchForw' => '1', 'REQ0JourneyStops2.0G' => '', 'REQ0JourneyStops2.0A' => '1', 'REQ0JourneyStopover2' => '', 'REQ0JourneyStops3.0G' => '', 'REQ0JourneyStops3.0A' => '1', 'REQ0JourneyStopover3' => '', 'REQ0JourneyStops4.0G' => '', 'REQ0JourneyStops4.0A' => '1', 'REQ0JourneyStopover4' => '', 'REQ0JourneyStops5.0G' => '', 'REQ0JourneyStops5.0A' => '1', 'REQ0JourneyStopover5' => '', 'existOptimizePrice' => '0', 'existUnsharpSearch' => 'yes', 'REQ0HafasChangeTime' => '0:1', 'existHafasAttrExc' => 'yes', 'REQ0JourneyProduct_prod_0' => '1', 'existProductBits0' => 'yes', 'REQ0JourneyProduct_prod_1' => '1', 'REQ0JourneyProduct_prod_2' => '1', 'REQ0JourneyProduct_prod_3' => '1', 'REQ0JourneyProduct_prod_4' => '1', 'REQ0JourneyProduct_prod_5' => '1', 'REQ0JourneyProduct_prod_6' => '1', 'REQ0JourneyProduct_prod_7' => '1', 'REQ0JourneyProduct_prod_8' => '1', 'REQ0JourneyProduct_prod_9' => '1', 'REQ0JourneyProduct_opt_section_0_list' => '0:0000', 'disableBaim' => 'yes', 'REQ0HafasHandicapLimit' => '4:4', 'changeQueryInputData' => 'yes', 'start' => 'Chercher correspondance'))); $crawler = new Crawler(utf8_encode((string) $response->getBody())); $overviews = array(); $date = ''; // Get overviews $crawler->filter('.hfs_overview .overview')->each(function (Crawler $node) use(&$overviews, &$date) { // Update date if (false !== strpos($node->getNode(0)->getAttribute('class'), 'dateHint')) { // Subtract 8 last chars $date = substr($text = trim($node->text()), ($len = strlen($text)) - 8, $len); return; } $overviews[] = array_filter(array($date, count($n = $node->filter('.time.departure')) ? substr(trim($n->text()), 0, 5) : null, count($n = $node->filter('.time.arrival')) ? substr(trim($n->text()), 0, 5) : null, count($n = $node->filter('.duration')) ? trim($n->text()) : null, count($n = $node->filter('.changes')) ? trim($n->text()) : null, count($n = $node->filter('.products')) ? trim($n->text()) : null, sprintf('%s%s', count($n = $node->filter('.top img')) ? trim($n->attr('alt')) : null, count($n = $node->filter('.him_icon img')) ? trim($n->attr('alt')) : null)), function ($v) { return $v !== null; }); }); // Combine overviews $_overviews = array(); for ($i = 0; $i < count($overviews) / 2; $i++) { $overview = $overviews[$i * 2] + $overviews[$i * 2 + 1]; ksort($overview); $_overviews[] = array_combine(array('date', 'departure', 'arrival', 'duration', 'change', 'product', 'infos'), $overview); } return $_overviews; }
public function format($datetime, $dateFormat = null, $timeFormat = null, $timezone = null, $locale = null) { $dt = null; $tz = null; if (null !== $timezone) { $tz = is_string($timezone) ? new \DateTimeZone($timezone) : $timezone; } if ($datetime instanceof \DateTimeImmutable) { $dt = new \DateTime($datetime->format('Y-m-d H:i:s'), $tz); } elseif (!$datetime instanceof \DateTime) { $dt = new \DateTime($datetime, $tz); } else { $dt = clone $datetime; } if (null === $tz) { $tz = $dt->getTimezone(); } if (null === $locale) { $locale = \Locale::getDefault(); } if (null === $dateFormat) { $dateFormat = \IntlDateFormatter::MEDIUM; } if (null === $timeFormat) { $timeFormat = \IntlDateFormatter::NONE; } $currentLocale = \Locale::getDefault(); \Locale::setDefault($locale); $formatter = new \IntlDateFormatter($locale, $dateFormat, $timeFormat, $tz); $result = $formatter->format($dt); \Locale::setDefault($currentLocale); return $result; }
/** * {@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; }
/** * Returns a string representation of the value. * * This method returns the equivalent PHP tokens for most scalar types * (i.e. "false" for false, "1" for 1 etc.). Strings are always wrapped * in double quotes ("). Objects, arrays and resources are formatted as * "object", "array" and "resource". If the parameter $prettyDateTime * is set to true, {@link \DateTime} objects will be formatted as * RFC-3339 dates ("Y-m-d H:i:s"). * * Be careful when passing message parameters to a constraint violation * that (may) contain objects, arrays or resources. These parameters * should only be displayed for technical users. Non-technical users * won't know what an "object", "array" or "resource" is and will be * confused by the violation message. * * @param mixed $value The value to format as string * @param bool $prettyDateTime Whether to format {@link \DateTime} * objects as RFC-3339 dates ("Y-m-d H:i:s") * * @return string The string representation of the passed value */ protected function formatValue($value, $prettyDateTime = false) { if ($prettyDateTime && $value instanceof \DateTime) { if (class_exists('IntlDateFormatter')) { $locale = \Locale::getDefault(); $formatter = new \IntlDateFormatter($locale, \IntlDateFormatter::MEDIUM, \IntlDateFormatter::SHORT); return $formatter->format($value); } return $value->format('Y-m-d H:i:s'); } if (is_object($value)) { return 'object'; } if (is_array($value)) { return 'array'; } if (is_string($value)) { return '"' . $value . '"'; } if (is_resource($value)) { return 'resource'; } if (null === $value) { return 'null'; } if (false === $value) { return 'false'; } if (true === $value) { return 'true'; } return (string) $value; }
function d(IntlDateFormatter $df) { global $ts; echo $df->format($ts), "\n"; var_dump($df->getTimeZoneID(), $df->getTimeZone()->getID()); echo "\n"; }
function openfit_base_preprocess_comment(&$variables) { $openfit_node_types = array('activity' => TRUE); if (!isset($variables['node']) || !isset($openfit_node_types[$variables['node']->type])) { return; } $comment = $variables['comment']; // Remove the standard comment links: reply, edit, delete unset($variables['content']['links']['comment']['#links']); // Add a delete menu if the user posted the comment or is admin global $user; if (user_access('administer comments') || $user->uid == $comment->uid) { $url = drupal_get_path_alias('node/' . $variables['node']->nid) . '/comments'; $variables['content']['links']['comment']['#links'] = array('comment-delete' => array('title' => ' ', 'href' => 'comment/' . $comment->cid . '/delete', 'query' => array('destination' => $url), 'html' => TRUE)); } // Display "XX ago" for posts less than 1 day, otherwise use locale to format datetime $ago = time() - $comment->created; if ($ago < 86400) { $variables['created'] = t('!interval ago', array('!interval' => format_interval(time() - $comment->created))); } else { $locale = OpenFitUserSetting::getCurrentUserLocale(); $fmt = new IntlDateFormatter($locale, IntlDateFormatter::SHORT, IntlDateFormatter::SHORT); $created = new DateTime('now'); $created->setTimestamp($comment->created); $variables['created'] = $fmt->format($created); } $variables['submitted'] = $variables['author'] . ' ' . '<time datetime="' . $variables['datetime'] . '" pubdate="pubdate">' . $variables['created'] . '</time>'; }
public function createView(ViewFactory $factory, $data, array $options) : ViewInterface { $dateFormat = $this->resolveFormat($options['date_format']); $timeFormat = $this->resolveFormat($options['time_format']); $formatter = new \IntlDateFormatter(\Locale::getDefault(), $dateFormat, $timeFormat, null, \IntlDateFormatter::GREGORIAN); return new DateTimeView($formatter->format($data), $data, $options['tag']); }
function d(IntlDateFormatter $df) { global $ts; echo $df->format($ts), "\n"; var_dump($df->getCalendar(), $df->getCalendarObject()->getType(), $df->getCalendarObject()->getTimeZone()->getId()); echo "\n"; }
public function __invoke($value, $format = 'Y-m-d H:i:s', $dateType = \IntlDateFormatter::SHORT, $timeType = \IntlDateFormatter::NONE) { $translator = $this->getServiceLocator()->getServiceLocator()->get('translator'); $locale = $translator->getTranslator()->getLocale(); $formatter = new \IntlDateFormatter($locale, $dateType, $timeType, null, null, $format); $date = new \DateTime($value); return $formatter->format($date); }
/** * {@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); }
private function formatDate(\DateTime $date) { if (null === $this->options['format']) { $locale = \Locale::getDefault(); $ftm = new \IntlDateFormatter($locale, \IntlDateFormatter::SHORT, \IntlDateFormatter::SHORT); return $ftm->format($date); } return $date->format($this->options['format']); }
public function ruDateFormat($dateRaw) { if ($dateRaw instanceof \DateTime) { $dateTime = $dateRaw; } else { $dateTime = new \DateTime($dateRaw); } $formatter = new \IntlDateFormatter('ru_RU', \IntlDateFormatter::NONE, \IntlDateFormatter::NONE); $formatter->setPattern('d MMMM YYYY'); return $formatter->format($dateTime); }
/** * @return array */ protected function getMonthNames() { $formatter = new \IntlDateFormatter(Yii::$app->language, \IntlDateFormatter::FULL, \IntlDateFormatter::FULL); $formatter->setPattern('MMMM'); $list = []; for ($i = 0; $i < 12; $i++) { $list[] = $formatter->format(mktime(0, 0, 0, $i, 1, 1970)); } $list[] = array_shift($list); return $list; }
protected static function normalize($datetime, array $options) { assert($datetime instanceof \DateTime || $datetime === null); if ($datetime === null) { return null; } if (is_string($options['format'])) { return $datetime->format($options['format']); } $dateFormatter = new \IntlDateFormatter($options['locale'], self::getIntlDateFormat($options['date_format']), self::getIntlDateFormat($options['time_format'])); return $dateFormatter->format($datetime); }
/** * @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); }
/** * Generates an array of localized month choices * * @param array $months The month numbers to generate * @return array The localized months respecting the configured * locale and date format */ protected function generateMonthChoices(array $months) { $pattern = $this->formatter->getPattern(); if (preg_match('/M+/', $pattern, $matches)) { $this->formatter->setPattern($matches[0]); $choices = array(); foreach ($months as $month) { $choices[$month] = $this->formatter->format(gmmktime(0, 0, 0, $month)); } $this->formatter->setPattern($pattern); } else { $choices = $this->generatePaddedChoices($months, 2); } return $choices; }
/** * @dataProvider getDayOfWeekNamesDataProvider */ public function testGetDayOfWeekNames($width, $locale, $defaultLocale = null) { $this->calendar->setLocale($locale); if (null !== $defaultLocale) { \Locale::setDefault($defaultLocale); } $actual = $this->calendar->getDayOfWeekNames($width); $this->assertCount(7, $actual); $widthToPatternMap = array(Calendar::WIDTH_ABBREVIATED => 'ccc', Calendar::WIDTH_SHORT => 'cccccc', Calendar::WIDTH_NARROW => 'ccccc', Calendar::WIDTH_WIDE => 'cccc'); $formatter = new \IntlDateFormatter($locale, null, null, 'UTC', \IntlDateFormatter::GREGORIAN, $widthToPatternMap[$width ?: Calendar::WIDTH_WIDE]); foreach ($actual as $dayNum => $dayName) { $checkDate = new \DateTime('2013/09/0' . $dayNum, new \DateTimeZone('UTC')); $expected = $formatter->format((int) $checkDate->format('U')); $this->assertEquals($expected, $actual[$dayNum], 'Incorrect day for day #' . $dayNum); } }
public function get_livedit() { $data = new DateTime(); $locale = 'it-it'; $fmt = new IntlDateFormatter($locale, IntlDateFormatter::SHORT, IntlDateFormatter::NONE); echo $fmt->format($data) . '<br>'; echo 'pattern is ' . $fmt->getPattern() . '<br>'; $locale = 'it_CH'; $fmt = new IntlDateFormatter($locale, IntlDateFormatter::SHORT, IntlDateFormatter::SHORT); echo $fmt->format($data) . '<br>'; echo 'pattern ' . $fmt->getPattern() . '<br>'; $locale = 'en-US'; $fmt = new IntlDateFormatter($locale, IntlDateFormatter::SHORT, IntlDateFormatter::SHORT); echo $fmt->format($data) . '<br>'; echo 'pattern ' . $fmt->getPattern() . '<br>'; die('NO'); }
/** * returns a string with date/time formatted accordingly to params or empty string if date is invalid * @param mixed $datetime * @param string $dateWidth width of the date pattern. It can be 'FULL', 'LONG', 'MEDIUM' and 'SHORT'. * If null, it means the date portion will NOT appear in the formatting result * @param string $timeWidth width of the time pattern. It can be 'FULL', 'LONG', 'MEDIUM' and 'SHORT'. * If null, it means the time portion will NOT appear in the formatting result * @return string */ public static function dateTime($datetime, $dateWidth = 'MEDIUM', $timeWidth = null) { $outputStr = ''; // To be used in the future with language and locale settings try { if (empty($datetime)) { throw new \Exception(); } if ($timeWidth === null) { $timeWidth = 'NONE'; } $df = new \IntlDateFormatter(\Locale::getDefault(), constant('IntlDateFormatter::' . strtoupper($dateWidth)), constant('IntlDateFormatter::' . strtoupper($timeWidth)), date_default_timezone_get()); $dateObj = new \DateTime($datetime); $outputStr = $df->format($dateObj->getTimestamp()); } catch (\Exception $e) { $outputStr = ''; } return $outputStr; }
/** * Здесь мы получаем уведомления о статусе платежа и отмечаем платеж как успешный (или не отмечаем) * Также рассылаем письма и билеты всем, кто был привязан к платежу * * @Route("/payment/interaction", name="payment_interaction") * @Template() * * @param Request $request * * @return array */ public function interactionAction(Request $request) { /** @var Payment $payment */ $payment = $this->getDoctrine()->getRepository('StfalconPaymentBundle:Payment')->findOneBy(array('id' => $request->get('ik_pm_no'))); if (!$payment) { throw new Exception('Платеж №' . $request->get('ik_pm_no') . ' не найден!'); } // @var InterkassaService $interkassa $interkassa = $this->container->get('stfalcon_event.interkassa.service'); if ($payment->isPending() && 1) { //$interkassa->checkPayment($payment, $request)) { $payment->markedAsPaid(); $em = $this->getDoctrine()->getManager(); $em->flush(); /** @var Ticket $ticket */ foreach ($payment->getTickets() as $ticket) { // розсилка квитків // @todo тут має смикатись сервіс який розсилає мильники про успішну оплату квитків + пдф в аттачі $user = $ticket->getUser(); $event = $ticket->getEvent(); $twig = $this->get('twig'); // @todo ачуметь.. екшн в одному бандлі. вьюшка в іншому $successPaymentTemplateContent = $twig->loadTemplate('StfalconEventBundle:Interkassa:success_payment.html.twig')->render(array('event_slug' => $event->getSlug())); $mail = new Mail(); $mail->addEvent($event); $mail->setText($successPaymentTemplateContent); // Get base template for email $emailTemplateContent = $twig->loadTemplate('StfalconEventBundle::email.html.twig'); $dateFormatter = new \IntlDateFormatter('ru-RU', \IntlDateFormatter::NONE, \IntlDateFormatter::NONE, date_default_timezone_get(), \IntlDateFormatter::GREGORIAN, 'd MMMM Y'); $text = $mail->replace(array('%fullname%' => $user->getFullName(), '%event%' => $event->getName(), '%date%' => $dateFormatter->format($event->getDate()), '%place%' => $event->getPlace())); $body = $emailTemplateContent->render(array('text' => $text, 'mail' => $mail, 'add_bottom_padding' => true)); /** @var $pdfGen \Stfalcon\Bundle\EventBundle\Helper\PdfGeneratorHelper */ $pdfGen = $this->get('stfalcon_event.pdf_generator.helper'); $html = $pdfGen->generateHTML($ticket); $outputFile = 'ticket-' . $event->getSlug() . '.pdf'; $message = \Swift_Message::newInstance()->setSubject($event->getName())->setFrom('*****@*****.**', 'Frameworks Days')->setTo($user->getEmail())->setBody($body, 'text/html')->attach(\Swift_Attachment::newInstance($pdfGen->generatePdfFile($html, $outputFile), $outputFile)); $this->get('mailer')->send($message); } return new Response('SUCCESS', 200); } return new Response('FAIL', 400); }
/** * Get a local date * @param int $timestamp * @param string $format * @param bool $allowInternational * @return bool|string */ public static function getLocalDate($timestamp = NULL, $format = NULL, $allowInternational = true) { if ($timestamp == NULL) { $timestamp = time(); } if ($format == NULL) { $format = DateManager::getDefaultFormat(); } if (DateManager::getCalendarType() == 'Jalali') { return JDateTime::date($format, $timestamp, false); } else { // Do we have the international date formatter? if ($allowInternational && Config::GetSetting('USE_INTL_DATEFORMAT') == 1 && Config::CheckIntlDateFormat()) { $formatter = new IntlDateFormatter(Config::GetSetting('DEFAULT_LANGUAGE'), IntlDateFormatter::FULL, IntlDateFormatter::FULL, Config::GetSetting('DEFAULT_TIMEZONE'), IntlDateFormatter::GREGORIAN, $format); return $formatter->format($timestamp); } else { return date($format, $timestamp); } } }
/** * * @param string $time * @param string $formatDate * @param string $formatTime * @param string $seperator * @return string */ public function __invoke($time = null, $formatDate = null, $formatTime = null, $pattern = null) { if (null === $time) { $datetime = new \DateTime(); } else { $datetime = new \DateTime($time); } if (null === $formatDate) { $formatDate = \IntlDateFormatter::LONG; } if ('LONG' === $formatDate) { $formatDate = \IntlDateFormatter::LONG; } if ('FULL' === $formatDate) { $formatDate = \IntlDateFormatter::FULL; } if ('MEDIUM' === $formatDate) { $formatDate = \IntlDateFormatter::MEDIUM; } if ('SHORT' === $formatDate) { $formatDate = \IntlDateFormatter::SHORT; } if (false === $formatDate) { $formatDate = \IntlDateFormatter::NONE; } if ('LONG' === $formatTime) { $formatTime = \IntlDateFormatter::LONG; } if ('SHORT' === $formatTime) { $formatTime = \IntlDateFormatter::SHORT; } if (null === $formatTime) { $formatTime = \IntlDateFormatter::NONE; } $fmt = new \IntlDateFormatter("de-DE", $formatDate, $formatTime); // , "Europe/Berlin", \IntlDateFormatter::GREGORIAN ); if (null !== $pattern) { $fmt->setPattern($pattern); } return $fmt->format($datetime); }
private function initDays() { $properties = array('daysChar' => array(), 'daysMedium' => array(), 'daysLong' => array()); $daysShort = array(); $formatter = new IntlDateFormatter($this->localeString, IntlDateFormatter::FULL, IntlDateFormatter::FULL, 'GMT', IntlDateFormatter::GREGORIAN, 'eeeee@eee@eeee'); // start date must be sunday so that sunday will be the first element in the array $date = new DateTime('1970-01-04', new DateTimeZone('GMT')); for ($i = 0; $i < 7; ++$i) { $names = $formatter->format((int) $date->format('U')); $date->modify('next day'); $splittedNames = explode('@', $names); foreach ($properties as $key => &$property) { $property[] = trim(array_shift($splittedNames), '. '); } } foreach ($properties['daysMedium'] as $name) { $daysShort[] = mb_substr($name, 0, 2, 'UTF-8'); } $properties['daysShort'] = $daysShort; $this->properties = array_merge($this->properties, $properties); }
/** * {@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; }
/** * {@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'; } } }
/** * @dataProvider dateAndTimeTypeProvider */ public function testDateAndTimeTypeIntl($timestamp, $datetype, $timetype, $expected) { $this->skipIfIntlExtensionIsNotLoaded(); $formatter = new \IntlDateFormatter('en', $datetype, $timetype, 'UTC'); $this->assertSame($expected, $formatter->format($timestamp)); }
/** * Convert normalized integer, float or date values to localized string representation * * Subclasses can support localized input formats by overriding setData() * where this method can be used to preprocess specific fields. It accepts * strictly normalized input data: * * - Integers must contain only digits. * - Floats must contain only digits and at most 1 dot, but not at the end * of the string. * - Dates must be passed as \DateTime objects or ISO date strings. * * Invalid input data is returned unmodified. The attached input filter * should take care of it. * * @param mixed $value Normalized input value * @param string $type Data type (integer, float, date). Any other value will be ignored. * @return mixed Localized or unmodified value */ public function localize($value, $type) { switch ($type) { case 'integer': if (ctype_digit((string) $value)) { $value = \Zend\Filter\StaticFilter::execute((int) $value, 'NumberFormat', array('type' => \NumberFormatter::TYPE_INT32)); } break; case 'float': if ($value !== null and $value !== '' and preg_match('/^([0-9]+)?(\\.[0-9]+)?$/', $value)) { $numberFormat = new \Zend\I18n\Filter\NumberFormat(); $numberFormat->getFormatter()->setAttribute(\NumberFormatter::MAX_FRACTION_DIGITS, 100); $value = $numberFormat->filter((double) $value); } break; case 'date': $formatter = new \IntlDateFormatter(\Locale::getDefault(), \IntlDateFormatter::MEDIUM, \IntlDateFormatter::NONE); if ($value instanceof \DateTime) { $value = $formatter->format($value); } elseif (\Zend\Validator\StaticValidator::execute($value, 'Date')) { $date = \DateTime::createFromFormat('Y-m-d', $value); if ($date) { $value = $formatter->format($date); } } break; } return $value; }