Пример #1
0
 /**
  * @param \DateInterval $interval
  * @return string
  */
 public static function format(\DateInterval $interval)
 {
     $string = $interval->format('%I:%S');
     if ($interval->h > 0) {
         $string = $interval->format('%H:') . $string;
     }
     if ($interval->d > 0) {
         $string = $interval->format('%D:') . $string;
     }
     return $string;
 }
Пример #2
0
 public function run()
 {
     // TODO initialize formatter settings at begin of request from user settings
     Yii::$app->formatter->timeZone = 'Europe/Berlin';
     $now = $this->getTimeComponent()->getStartTime();
     $end = clone $now;
     $end->add($this->duration);
     // TODO introduce constant for DateInterval format
     $strDuration = $this->duration->format('%H:%I:%S');
     $strEnd = Yii::$app->formatter->asDatetime($end);
     return "<div>Duration: {$strDuration}, until: {$strEnd}</div>";
 }
 /**
  * Format a date (or interval) to a string with a given format
  *
  * See formatting options as in PHP date()
  *
  * @param integer|string|\DateTime|\DateInterval $date
  * @param string $format
  * @return string
  */
 public function format($date, $format)
 {
     if ($date instanceof \DateTimeInterface) {
         return $date->format($format);
     } elseif ($date instanceof \DateInterval) {
         return $date->format($format);
     } elseif ($date === 'now') {
         return date($format);
     } else {
         $timestamp = (int) $date;
         return date($format, $timestamp);
     }
 }
Пример #4
0
 /**
  *
  * Return duration in seconds
  *
  * @return int, duration in seconds
  */
 public function getDuration()
 {
     $this->initialRequest();
     if (isset($this->item['contentDetails']['duration'])) {
         $date = new \DateInterval($this->item['contentDetails']['duration']);
         $ret = 0;
         $ret += (int) $date->format('%d') * 86400;
         $ret += (int) $date->format('%h') * 3600;
         $ret += (int) $date->format('%i') * 60;
         $ret += (int) $date->format('%s');
         return $ret;
     } else {
         $this->onApiBadInterpretation("contentDetails.duration not found");
     }
 }
Пример #5
0
 public function formatWithoutZeroes()
 {
     // Each argument may have only one % parameter
     // Result does not handle %R or %r -- but you can retrieve that information using $this->format('%R') and using your own logic
     $parts = array();
     foreach (func_get_args() as $arg) {
         $pre = mb_substr($arg, 0, mb_strpos($arg, '%'));
         $param = mb_substr($arg, mb_strpos($arg, '%'), 2);
         $post = mb_substr($arg, mb_strpos($arg, $param) + mb_strlen($param));
         $num = intval(parent::format($param));
         $open = preg_quote($this->pluralCheck[0], '/');
         $close = preg_quote($this->pluralCheck[1], '/');
         $pattern = "/{$open}(.*){$close}/";
         list($pre, $post) = preg_replace($pattern, $num == 1 ? $this->singularReplacement : '$1', array($pre, $post));
         if ($num != 0) {
             $parts[] = $pre . $num . $post;
         }
     }
     $output = '';
     $l = count($parts);
     foreach ($parts as $i => $part) {
         $output .= $part . ($i < $l - 2 ? $this->separator : ($l == 2 ? $this->finalSeparator2 : ($i == $l - 2 ? $this->finalSeparator : '')));
     }
     return $output;
 }
Пример #6
0
 public function format($format)
 {
     $callback = function ($value) {
         if ($value[0] === '%tm') {
             return $this->total_months;
         }
         if ($value[0] === '%tw') {
             return $this->total_weeks;
         }
         if ($value[0] === '%a' || $value[0] === '%td') {
             return $this->total_days;
         }
         if ($value[0] === '%th') {
             return $this->total_hours;
         }
         if ($value[0] === '%ti') {
             return $this->total_minutes;
         }
         if ($value[0] === '%ts') {
             return $this->total_seconds;
         }
         return parent::format($value[0]);
     };
     return preg_replace_callback('/%(?:[a-z]{1,2})+/i', $callback, $format);
 }
Пример #7
0
 public function testIsGreaterThanOrEqualTo()
 {
     $this->given($asserter = $this->newTestedInstance)->then->exception(function () use($asserter) {
         $asserter->isGreaterThanOrEqualTo(new \DateInterval('P1D'));
     })->isInstanceOf('mageekguy\\atoum\\exceptions\\logic')->hasMessage('Interval is undefined')->if($asserter->setWith(new \DateInterval('P1Y')))->then->object($asserter->isGreaterThanOrEqualTo(new \DateInterval('P1M')))->isIdenticalTo($asserter)->exception(function () use($asserter, &$interval) {
         $asserter->isGreaterThanOrEqualTo($interval = new \DateInterval('P2Y'));
     })->isInstanceOf('mageekguy\\atoum\\asserter\\exception')->hasMessage('Interval ' . $asserter . ' is not greater than or equal to ' . $interval->format('%Y/%M/%D %H:%I:%S'));
 }
Пример #8
0
 /**
  * @param $format
  * @return mixed|string
  */
 public function format($format)
 {
     $formatted = parent::format($format);
     if ($this instanceof DateInterval && property_exists($this, 'u') && $this->u != 0) {
         $formatted = preg_replace('/([0-9]{1,2})S/', "\$1." . str_pad($this->u, 6, 0, STR_PAD_LEFT) . 'S', $formatted);
     }
     return $formatted;
 }
Пример #9
0
 public function getListSongs($search)
 {
     $youtubeResults = $this->getResponse($search, 'search');
     foreach ($youtubeResults['items'] as $subarray) {
         $youtubeResult = $this->getResponse($subarray['id']['videoId'], 'video');
         //pour obtenir la durée de la vidéo on exécute une requête sur les détails de la vidéo référencée par la videoId
         $duration = new \DateInterval($youtubeResult['items'][0]['contentDetails']['duration']);
         if ((int) $duration->format('%h') < 1 && (int) $duration->format('%d') < 1) {
             $duration = ((int) $duration->format('%h') * 3600 + (int) $duration->format('%i')) * 60 + (int) $duration->format('%s');
             //on récupère la durée en secondes
             $song = new Song();
             $song->setTitle($subarray['snippet']['title'])->setReference($subarray['id']['videoId'])->setProvider('youtube')->setAlbumCover($subarray['snippet']['thumbnails']['default']['url'])->setPreview('https://www.youtube.com/watch?v=' . $subarray['id']['videoId'])->setDuration($duration);
             $listSongs[] = $song;
             //return $listSongs;
         }
     }
     return $listSongs;
 }
Пример #10
0
 /**
  * {@inheritdoc}
  */
 public function buildPropertyBag()
 {
     $this->properties = new PropertyBag();
     // mandatory information
     $this->properties->set('UID', $this->uniqueId);
     $this->properties->add($this->buildDateTimeProperty('DTSTAMP', $this->dtStamp ?: new \DateTime()));
     $this->properties->add($this->buildDateTimeProperty('DTSTART', $this->dtStart, $this->noTime));
     $this->properties->set('SEQUENCE', $this->sequence);
     $this->properties->set('TRANSP', $this->transparency);
     if ($this->status) {
         $this->properties->set('STATUS', $this->status);
     }
     // An event can have a 'dtend' or 'duration', but not both.
     if (null != $this->dtEnd) {
         $this->properties->add($this->buildDateTimeProperty('DTEND', $this->dtEnd, $this->noTime));
     } elseif (null != $this->duration) {
         $this->properties->set('DURATION', $this->duration->format('P%dDT%hH%iM%sS'));
     }
     // optional information
     if (null != $this->url) {
         $this->properties->set('URL', $this->url);
     }
     if (null != $this->location) {
         $this->properties->set('LOCATION', $this->location);
         if (null != $this->locationGeo) {
             $this->properties->add(new Property('X-APPLE-STRUCTURED-LOCATION', 'geo:' . $this->locationGeo, array('VALUE' => 'URI', 'X-ADDRESS' => $this->location, 'X-APPLE-RADIUS' => 49, 'X-TITLE' => $this->locationTitle)));
         }
     }
     if (null != $this->summary) {
         $this->properties->set('SUMMARY', $this->summary);
     }
     if (null != $this->attendee) {
         $this->properties->set('ATTENDEE', $this->attendee);
     }
     if (null != $this->description) {
         $this->properties->set('DESCRIPTION', $this->description);
     }
     if (null != $this->recurrenceRule) {
         $this->properties->set('RRULE', $this->recurrenceRule);
     }
     if ($this->cancelled) {
         $this->properties->set('STATUS', 'CANCELLED');
     }
     if (null != $this->organizer) {
         $this->properties->set('ORGANIZER', $this->organizer);
     }
     if ($this->noTime) {
         $this->properties->set('X-MICROSOFT-CDO-ALLDAYEVENT', 'TRUE');
     }
     if ($this->created) {
         $this->properties->add($this->buildDateTimeProperty('CREATED', $this->created));
     }
     if ($this->modified) {
         $this->properties->add($this->buildDateTimeProperty('LAST-MODIFIED', $this->modified));
     }
 }
Пример #11
0
 /**
  * {@inheritdoc}
  */
 public function setDuration(\DateInterval $duration, $notify = TRUE)
 {
     // Generate an ISO 8601 formatted string as supported by
     // DateInterval::__construct() and setValue().
     $this->value = $duration->format('%rP%yY%mM%dDT%hH%mM%sS');
     // Notify the parent of any changes.
     if ($notify && isset($this->parent)) {
         $this->parent->onChange($this->name);
     }
 }
 /**
  * Transforms a DateInterval object into a date string with the configured format.
  *
  * @param \DateInterval $value A DateInterval object
  *
  * @return string An ISO 8601 or relative date string like date interval presentation
  *
  * @throws UnexpectedTypeException If the given value is not a \DateInterval instance.
  */
 public function transform($value)
 {
     if (null === $value) {
         return '';
     }
     if (!$value instanceof \DateInterval) {
         throw new UnexpectedTypeException($value, '\\DateInterval');
     }
     return $value->format($this->format);
 }
Пример #13
0
 public function getDefaultLength()
 {
     $dateString = $this->webstream->getDbLength();
     $arr = explode(":", $dateString);
     if (count($arr) == 3) {
         list($hours, $min, $sec) = $arr;
         $di = new DateInterval("PT{$hours}H{$min}M{$sec}S");
         return $di->format("%Hh %Im");
     }
     return "";
 }
Пример #14
0
 function format_interval(DateInterval $interval)
 {
     $result = "";
     if ($interval->y) {
         $result .= $interval->format("%y years ");
     }
     if ($interval->m) {
         $result .= $interval->format("%m months ");
     }
     if ($interval->d) {
         $result .= $interval->format("%d days ");
     }
     if ($interval->h) {
         $result .= $interval->format("%h hours ");
     }
     if ($interval->i) {
         $result .= $interval->format("%i minutes ");
     }
     return $result;
 }
Пример #15
0
 private function _formatInterval(DateInterval $interval)
 {
     $result = "";
     if ($interval->y) {
         $result .= $interval->format("<span>%y</span>y ");
     }
     if ($interval->m) {
         $result .= $interval->format("<span>%m</span>m ");
     }
     if ($interval->d) {
         $result .= $interval->format("<span>%d</span>d ");
     }
     if ($interval->h) {
         $result .= $interval->format("<span>%h</span>h ");
     }
     if ($interval->i) {
         $result .= $interval->format("<span>%i</span>m ");
     }
     // if ($interval->s) { $result .= $interval->format("<span>%s</span>s "); }
     return $result;
 }
Пример #16
0
 public function index()
 {
     /** @var WP_Locale $wp_locale */
     global $wp_locale;
     $this->enqueueStyles(array('frontend' => array('css/intlTelInput.css'), 'module' => array('css/calendar.css', 'css/fullcalendar.min.css'), 'backend' => array('css/chosen.min.css', 'css/jquery-ui-theme/jquery-ui.min.css', 'css/bookly.main-backend.css', 'bootstrap/css/bootstrap.min.css')));
     $this->enqueueScripts(array('backend' => array('js/angular-1.3.11.min.js' => array('jquery'), 'js/angular-ui-date-0.0.7.js' => array('ab-angular-1.3.11.min.js'), 'js/ng-new_customer_dialog.js' => array('ab-angular-1.3.11.min.js'), 'js/moment.min.js' => array('jquery'), 'bootstrap/js/bootstrap.min.js' => array('jquery'), 'js/chosen.jquery.min.js' => array('jquery')), 'module' => array('js/ng-app.js' => array('ab-angular-ui-date-0.0.7.js', 'jquery-ui-datepicker', 'jquery-ui-widget', 'jquery-ui-dialog'), 'js/fullcalendar.min.js' => array('ab-moment.min.js'), 'js/fc-multistaff-view.js' => array('ab-fullcalendar.min.js'), 'js/calendar.js' => array('ab-fc-multistaff-view.js', 'ab-intlTelInput.min.js')), 'frontend' => array('js/intlTelInput.min.js' => array('jquery'))));
     $slot_length_minutes = get_option('ab_settings_time_slot_length', '15');
     $slot = new DateInterval('PT' . $slot_length_minutes . 'M');
     $this->staff_members = AB_Utils::isCurrentUserAdmin() ? AB_Staff::query()->sortBy('position')->find() : AB_Staff::query()->where('wp_user_id', get_current_user_id())->find();
     wp_localize_script('ab-calendar.js', 'BooklyL10n', array('slotDuration' => $slot->format('%H:%I:%S'), 'shortMonths' => array_values($wp_locale->month_abbrev), 'longMonths' => array_values($wp_locale->month), 'shortDays' => array_values($wp_locale->weekday_abbrev), 'longDays' => array_values($wp_locale->weekday), 'AM' => $wp_locale->meridiem['AM'], 'PM' => $wp_locale->meridiem['PM'], 'dpDateFormat' => AB_DateTimeUtils::convertFormat('date', AB_DateTimeUtils::FORMAT_JQUERY_DATEPICKER), 'mjsDateFormat' => AB_DateTimeUtils::convertFormat('date', AB_DateTimeUtils::FORMAT_MOMENT_JS), 'mjsTimeFormat' => AB_DateTimeUtils::convertFormat('time', AB_DateTimeUtils::FORMAT_MOMENT_JS), 'today' => __('Today', 'bookly'), 'week' => __('Week', 'bookly'), 'day' => __('Day', 'bookly'), 'month' => __('Month', 'bookly'), 'allDay' => __('All Day', 'bookly'), 'noStaffSelected' => __('No staff selected', 'bookly'), 'newAppointment' => __('New appointment', 'bookly'), 'editAppointment' => __('Edit appointment', 'bookly'), 'are_you_sure' => __('Are you sure?', 'bookly'), 'startOfWeek' => (int) get_option('start_of_week'), 'country' => get_option('ab_settings_phone_default_country'), 'intlTelInput_utils' => plugins_url('intlTelInput.utils.js', AB_PATH . '/frontend/resources/js/intlTelInput.utils.js')));
     $this->render('calendar');
 }
Пример #17
0
 /**
  * Description
  *
  * @param  string $response Response from Shipping service server
  * @return array  Array of shipping rates
  */
 private function _getRates($response)
 {
     // Parse XML message returned by the UPS post server.
     $doc = new \XMLDocument();
     $xp = new \XMLParser();
     $xp->setDocument($doc);
     $xp->parse($response);
     $doc = $xp->getDocument();
     $return = array();
     if (is_object($doc->root)) {
         $root = $doc->getRoot();
         if ($root->name != 'res:ErrorResponse') {
             $path = array('GetQuoteResponse', 'BkgDetails');
             foreach ($path as $node) {
                 $root = $root->getElementsByName($node);
                 if ($root) {
                     $root = $root[0];
                 } else {
                     break;
                 }
             }
             if ($root) {
                 $shipments = $root->getElementsByName('QtdShp');
                 foreach ($shipments as $shipment) {
                     $name = $shipment->getValueByPath('ProductShortName');
                     $code = $shipment->getValueByPath('GlobalProductCode');
                     $rate = floatval($shipment->getValueByPath('ShippingCharge'));
                     $date = $shipment->getValueByPath('DeliveryDate');
                     $time = $shipment->getValueByPath('DeliveryTime');
                     if ($time) {
                         $time = new \DateInterval($time);
                         $date .= ', ' . $time->format('%H:%I');
                     }
                     if ($rate) {
                         $return[$code] = array('rate' => $rate, 'delivery_time' => $date, 'name' => $name);
                     }
                 }
             }
         }
     }
     return $return;
 }
Пример #18
0
 /**
  * Calculate seconds from interval
  *
  * @param \DateInterval $interval
  * @return integer
  */
 private function intervalToSeconds(\DateInterval $interval)
 {
     $seconds = $interval->format('%s');
     $multiplier = 60;
     $seconds += $interval->format('%i') * $multiplier;
     $multiplier *= 60;
     $seconds += $interval->format('%h') * $multiplier;
     $multiplier *= 24;
     $seconds += $interval->format('%d') * $multiplier;
     $multiplier *= 30;
     $seconds += $interval->format('%m') * $multiplier;
     $multiplier *= 12;
     $seconds += $interval->format('%y') * $multiplier;
     return $seconds;
 }
 /**
  * Transforms a normalized date interval into an interval array.
  *
  * @param \DateInterval $dateInterval Normalized date interval.
  *
  * @return array Interval array.
  *
  * @throws UnexpectedTypeException If the given value is not a \DateInterval instance.
  */
 public function transform($dateInterval)
 {
     if (null === $dateInterval) {
         return array_intersect_key(array('years' => '', 'months' => '', 'weeks' => '', 'days' => '', 'hours' => '', 'minutes' => '', 'seconds' => '', 'invert' => false), array_flip($this->fields));
     }
     if (!$dateInterval instanceof \DateInterval) {
         throw new UnexpectedTypeException($dateInterval, '\\DateInterval');
     }
     $result = array();
     foreach (self::$availableFields as $field => $char) {
         $result[$field] = $dateInterval->format('%' . ($this->pad ? strtoupper($char) : $char));
     }
     if (in_array('weeks', $this->fields, true)) {
         $result['weeks'] = 0;
         if (isset($result['days']) && (int) $result['days'] >= 7) {
             $result['weeks'] = (string) floor($result['days'] / 7);
             $result['days'] = (string) ($result['days'] % 7);
         }
     }
     $result['invert'] = '-' === $result['invert'];
     $result = array_intersect_key($result, array_flip($this->fields));
     return $result;
 }
Пример #20
0
 /**
  * @Route("/pokerconnection", name="pokerConnection")
  * @Template()
  */
 public function pokerConnectionAction(Request $request)
 {
     $em = $this->getDoctrine()->getManager();
     $user_id = $request->query->get('user_id');
     $user = $em->getRepository('AppBundle:User')->find($user_id);
     $project_id = $request->query->get('project_id');
     $project = $em->getRepository('ScrumatorBackendBundle:Project')->find($project_id);
     if ($project && $user) {
         $user_project_link = $em->getRepository('ScrumatorBackendBundle:user_project_link')->findOneBy(array('project' => $project, 'user' => $user));
         if ($user_project_link) {
             $user_project_link->setLastConnection();
             $em->persist($user_project_link);
             $em->flush();
         }
     } else {
         $user_project_link = NULL;
     }
     $users_project_link = $em->getRepository('ScrumatorBackendBundle:user_project_link')->findBy(array('project' => $project));
     $result = [];
     $today = new \DateTime('now');
     $maxInterval = new \DateInterval('PT30S');
     foreach ($users_project_link as $value) {
         $connected = FALSE;
         if ($value->getLastConnection()) {
             $interval = $value->getLastConnection()->diff($today);
             if ($interval->format('%Y%m%d%H%I%S') < $maxInterval->format('%Y%m%d%H%I%S')) {
                 $connected = TRUE;
             }
         } else {
             $interval = NULL;
         }
         $result[$value->getUser()->getId()] = array('lastConnection' => $value->getLastConnection(), 'interval' => $interval, 'connected' => $connected);
     }
     $reponse = new JsonResponse();
     $reponse->setData($result);
     return $reponse;
 }
Пример #21
0
 public function format_interval(\DateInterval $interval)
 {
     $result = "";
     if ($interval->y) {
         $result .= $interval->format("%y año(s) ");
     }
     if ($interval->m) {
         $result .= $interval->format("%m mese(s) ");
     }
     if ($interval->d) {
         $result .= $interval->format("%d dia(s) ");
     }
     // if ($interval->h) { $result .= $interval->format("%h hour(s) "); }
     // if ($interval->i) { $result .= $interval->format("%i minute(s) "); }
     // if ($interval->s) { $result .= $interval->format("%s second(s) "); }
     return $result;
 }
Пример #22
0
 /**
  * Parse 1 VEvent
  * @param ical_vevent $event
  * @param SyncAppointment(Exception) $message
  * @param int $truncsize
  */
 private function _ParseVEventToSyncObject($event, $message, $truncsize)
 {
     //Defaults
     $message->busystatus = "2";
     $properties = $event->GetProperties();
     foreach ($properties as $property) {
         switch ($property->Name()) {
             case "LAST-MODIFIED":
                 $message->dtstamp = Utils::MakeUTCDate($property->Value());
                 break;
             case "DTSTART":
                 $message->starttime = Utils::MakeUTCDate($property->Value(), Utils::ParseTimezone($property->GetParameterValue("TZID")));
                 if (strlen($property->Value()) == 8) {
                     $message->alldayevent = "1";
                 }
                 break;
             case "SUMMARY":
                 $message->subject = $property->Value();
                 break;
             case "UID":
                 $message->uid = $property->Value();
                 break;
             case "ORGANIZER":
                 $org_mail = str_ireplace("MAILTO:", "", $property->Value());
                 $message->organizeremail = $org_mail;
                 $org_cn = $property->GetParameterValue("CN");
                 if ($org_cn) {
                     $message->organizername = $org_cn;
                 }
                 break;
             case "LOCATION":
                 $message->location = $property->Value();
                 break;
             case "DTEND":
                 $message->endtime = Utils::MakeUTCDate($property->Value(), Utils::ParseTimezone($property->GetParameterValue("TZID")));
                 if (strlen($property->Value()) == 8) {
                     $message->alldayevent = "1";
                 }
                 break;
             case "DURATION":
                 if (!isset($message->endtime)) {
                     $start = date_create("@" . $message->starttime);
                     $val = str_replace("+", "", $property->Value());
                     $interval = new DateInterval($val);
                     $message->endtime = date_timestamp_get(date_add($start, $interval));
                 }
                 break;
             case "RRULE":
                 $message->recurrence = $this->_ParseRecurrence($property->Value(), "vevent");
                 break;
             case "CLASS":
                 switch ($property->Value()) {
                     case "PUBLIC":
                         $message->sensitivity = "0";
                         break;
                     case "PRIVATE":
                         $message->sensitivity = "2";
                         break;
                     case "CONFIDENTIAL":
                         $message->sensitivity = "3";
                         break;
                 }
                 break;
             case "TRANSP":
                 switch ($property->Value()) {
                     case "TRANSPARENT":
                         $message->busystatus = "0";
                         break;
                     case "OPAQUE":
                         $message->busystatus = "2";
                         break;
                 }
                 break;
                 // SYNC_POOMCAL_MEETINGSTATUS
                 // Meetingstatus values
                 //  0 = is not a meeting
                 //  1 = is a meeting
                 //  3 = Meeting received
                 //  5 = Meeting is canceled
                 //  7 = Meeting is canceled and received
                 //  9 = as 1
                 // 11 = as 3
                 // 13 = as 5
                 // 15 = as 7
             // SYNC_POOMCAL_MEETINGSTATUS
             // Meetingstatus values
             //  0 = is not a meeting
             //  1 = is a meeting
             //  3 = Meeting received
             //  5 = Meeting is canceled
             //  7 = Meeting is canceled and received
             //  9 = as 1
             // 11 = as 3
             // 13 = as 5
             // 15 = as 7
             case "STATUS":
                 switch ($property->Value()) {
                     case "TENTATIVE":
                         $message->meetingstatus = "3";
                         // was 1
                         break;
                     case "CONFIRMED":
                         $message->meetingstatus = "1";
                         // was 3
                         break;
                     case "CANCELLED":
                         $message->meetingstatus = "5";
                         // could also be 7
                         break;
                 }
                 break;
             case "ATTENDEE":
                 $attendee = new SyncAttendee();
                 $att_email = str_ireplace("MAILTO:", "", $property->Value());
                 $attendee->email = $att_email;
                 $att_cn = $property->GetParameterValue("CN");
                 if ($att_cn) {
                     $attendee->name = $att_cn;
                 }
                 if (isset($message->attendees) && is_array($message->attendees)) {
                     $message->attendees[] = $attendee;
                 } else {
                     $message->attendees = array($attendee);
                 }
                 break;
             case "DESCRIPTION":
                 if (Request::GetProtocolVersion() >= 12.0) {
                     $message->asbody = new SyncBaseBody();
                     $message->asbody->data = str_replace("\n", "\r\n", str_replace("\r", "", Utils::ConvertHtmlToText($property->Value())));
                     // truncate body, if requested
                     if (strlen($message->asbody->data) > $truncsize) {
                         $message->asbody->truncated = 1;
                         $message->asbody->data = Utils::Utf8_truncate($message->asbody->data, $truncsize);
                     } else {
                         $message->asbody->truncated = 0;
                     }
                     $message->nativebodytype = SYNC_BODYPREFERENCE_PLAIN;
                 } else {
                     $body = $property->Value();
                     // truncate body, if requested
                     if (strlen($body) > $truncsize) {
                         $body = Utils::Utf8_truncate($body, $truncsize);
                         $message->bodytruncated = 1;
                     } else {
                         $body = $body;
                         $message->bodytruncated = 0;
                     }
                     $body = str_replace("\n", "\r\n", str_replace("\r", "", $body));
                     $message->body = $body;
                 }
                 break;
             case "CATEGORIES":
                 $categories = explode(",", $property->Value());
                 $message->categories = $categories;
                 break;
             case "EXDATE":
                 $exception = new SyncAppointmentException();
                 $exception->deleted = "1";
                 $exception->exceptionstarttime = Utils::MakeUTCDate($property->Value());
                 if (!isset($message->exceptions)) {
                     $message->exceptions = array();
                 }
                 $message->exceptions[] = $exception;
                 break;
                 //We can ignore the following
             //We can ignore the following
             case "PRIORITY":
             case "SEQUENCE":
             case "CREATED":
             case "DTSTAMP":
             case "X-MOZ-GENERATION":
             case "X-MOZ-LASTACK":
             case "X-LIC-ERROR":
             case "RECURRENCE-ID":
                 break;
             default:
                 ZLog::Write(LOGLEVEL_DEBUG, sprintf("BackendCalDAV->_ParseVEventToSyncObject(): '%s' is not yet supported.", $property->Name()));
         }
     }
     $valarm = current($event->GetComponents("VALARM"));
     if ($valarm) {
         $properties = $valarm->GetProperties();
         foreach ($properties as $property) {
             if ($property->Name() == "TRIGGER") {
                 $parameters = $property->Parameters();
                 if (array_key_exists("VALUE", $parameters) && $parameters["VALUE"] == "DATE-TIME") {
                     $trigger = date_create("@" . Utils::MakeUTCDate($property->Value()));
                     $begin = date_create("@" . $message->starttime);
                     $interval = date_diff($begin, $trigger);
                     $message->reminder = $interval->format("%i") + $interval->format("%h") * 60 + $interval->format("%a") * 60 * 24;
                 } elseif (!array_key_exists("VALUE", $parameters) || $parameters["VALUE"] == "DURATION") {
                     $val = str_replace("-", "", $property->Value());
                     $interval = new DateInterval($val);
                     $message->reminder = $interval->format("%i") + $interval->format("%h") * 60 + $interval->format("%a") * 60 * 24;
                 }
             }
         }
     }
     return $message;
 }
Пример #23
0
 public static function assertDateIntervalEquals(\DateInterval $expected, \DateInterval $actual)
 {
     self::assertEquals($expected->format('%RP%yY%mM%dDT%hH%iM%sS'), $actual->format('%RP%yY%mM%dDT%hH%iM%sS'));
 }
Пример #24
0
 /**
  * @dataProvider provideSimpleSpec
  */
 public function testConstructConvertSimpleSpec(\DateInterval $expectedInterval, $testSpec)
 {
     $format = '%R %Y %M %D %H %I %S';
     $actualInterval = new DateInterval($testSpec);
     $this->assertEquals($expectedInterval->format($format), $actualInterval->format($format));
 }
Пример #25
0
	/**
	 * Returns a formatted date interval. If $fullInterval is set true, the
	 * complete interval is returned, otherwise a rounded interval is used.
	 * 
	 * @param	\DateInterval	$interval
	 * @param	boolean		$fullInterval
	 * @return	string
	 */
	public static function formatInterval(\DateInterval $interval, $fullInterval = false) {
		$years = $interval->format('%y');
		$months = $interval->format('%m');
		$days = $interval->format('%d');
		$weeks = floor($days / 7);
		$hours = $interval->format('%h');
		$minutes = $interval->format('%i');
		switch ($interval->format('%R')) {
			case '+':
				$direction = 'past';
			break;
			case '-':
				$direction = 'future';
			break;
		}
		
		if ($fullInterval) {
			return WCF::getLanguage()->getDynamicVariable('wcf.date.interval.full.'.$direction, array(
				'days' => $days - 7 * $weeks,
				'firstElement' => $years ? 'years' : ($months ? 'months' : ($weeks ? 'weeks' : ($days ? 'days' : ($hours ? 'hours' : 'minutes')))),
				'hours' => $hours,
				'lastElement' => !$minutes ? (!$hours ? (!$days ? (!$weeks ? (!$months ? 'years' : 'months') : 'weeks') : 'days') : 'hours') : 'minutes',
				'minutes' => $minutes,
				'months' => $months,
				'weeks' => $weeks,
				'years' => $years
			));
		}
		
		if ($years) {
			return WCF::getLanguage()->getDynamicVariable('wcf.date.interval.years.'.$direction, array(
				'years' => $years
			));
		}
		
		if ($months) {
			return WCF::getLanguage()->getDynamicVariable('wcf.date.interval.months.'.$direction, array(
				'months' => $months
			));
		}
		
		if ($weeks) {
			return WCF::getLanguage()->getDynamicVariable('wcf.date.interval.weeks.'.$direction, array(
				'weeks' => $weeks
			));
		}
		
		if ($days) {
			return WCF::getLanguage()->getDynamicVariable('wcf.date.interval.days.'.$direction, array(
				'days' => $days
			));
		}
		
		if ($hours) {
			return WCF::getLanguage()->getDynamicVariable('wcf.date.interval.hours.'.$direction, array(
				'hours' => $hours
			));
		}
		
		return WCF::getLanguage()->getDynamicVariable('wcf.date.interval.minutes.'.$direction, array(
			'minutes' => $minutes
		));
	}
Пример #26
0
/**
 * Converts a date to the given format.
 *
 * <pre>
 *   {{ post.published_at|date("m/d/Y") }}
 * </pre>
 *
 * @param Twig_Environment                               $env      A Twig_Environment instance
 * @param DateTime|DateTimeInterface|DateInterval|string $date     A date
 * @param string|null                                    $format   The target format, null to use the default
 * @param DateTimeZone|string|null|false                 $timezone The target timezone, null to use the default, false to leave unchanged
 *
 * @return string The formatted date
 */
function twig_date_format_filter(Twig_Environment $env, $date, $format = null, $timezone = null)
{
    if (null === $format) {
        $formats = $env->getExtension('core')->getDateFormat();
        $format = $date instanceof DateInterval ? $formats[1] : $formats[0];
    }
    if ($date instanceof DateInterval) {
        return $date->format($format);
    }
    return twig_date_converter($env, $date, $timezone)->format($format);
}
<?php

$d = new DateTime('@100000000000');
var_dump($d->format('Y-m-d H:i:s U'));
var_dump($d->getTimestamp());
var_dump($d->format('U'));
$d->setTimestamp(100000000000);
var_dump($d->format('Y-m-d H:i:s U'));
var_dump($d->getTimestamp());
$i = new DateInterval('PT100000000000S');
var_dump($i->format('%s'));
Пример #28
0
 /**
  * Formatting for current date interval
  * @param $format
  * @return string
  */
 public function format($format)
 {
     $format = str_replace('%U', sprintf("%06d", $this->u), $format);
     $format = str_replace('%u', sprintf("%d", intval($this->u)), $format);
     return parent::format($format);
 }
Пример #29
0
 /**
  * Formats date-time interval for use in a SQL statement.
  */
 public function formatDateInterval(\DateInterval $value)
 {
     return $value->format("'%r%h:%I:%S'");
 }
 /**
  * Returns replacements for pattern segments based on data from a given
  * video data object.
  *
  * @param object $entry
  * @return array
  */
 protected function getReplacements($entry)
 {
     $link = 'https://youtu.be/' . $entry->id;
     $title = $entry->snippet->title;
     $author = $entry->snippet->channelTitle;
     $published = date($this->publishedFormat, strtotime($entry->snippet->publishedAt));
     $views = number_format($entry->statistics->viewCount, 0);
     $likes = number_format($entry->statistics->likeCount, 0);
     $dislikes = number_format($entry->statistics->dislikeCount, 0);
     $favorites = number_format($entry->statistics->favoriteCount, 0);
     $comments = number_format($entry->statistics->commentCount, 0);
     $durationInterval = new \DateInterval($entry->contentDetails->duration);
     $duration = $durationInterval->format($this->durationFormat);
     return array('%link%' => $link, '%title%' => $title, '%author%' => $author, '%published%' => $published, '%views%' => $views, '%likes%' => $likes, '%dislikes%' => $dislikes, '%favorites%' => $favorites, '%comments%' => $comments, '%duration%' => $duration);
 }