本文整理汇总了PHP中DateTimeImmutable类的典型用法代码示例。如果您正苦于以下问题:PHP DateTimeImmutable类的具体用法?PHP DateTimeImmutable怎么用?PHP DateTimeImmutable使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了DateTimeImmutable类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。
示例1: get_news
function get_news()
{
global $NEWS;
foreach ($NEWS as $i) {
#var_dump($i);
$class = $i['isImportant'] ? 'important' : '';
$now = new DateTimeImmutable('now');
$date = new DateTimeImmutable($i['date']);
$d_start = array_key_exists('dateOn', $i) ? new DateTime($i['dateOn']) : $now;
$d_end = array_key_exists('dateOff', $i) ? new DateTime($i['dateOff']) : $date->add(new DateInterval('P14D'));
#var_dump($date);
#var_dump($d_start);
#var_dump($d_end);
if ($now < $d_start or $now > $d_end) {
continue;
}
echo <<<HTML
<li class="{$class}">
<div class="newsitem">
<strong>{$i['title']}</strong>
<br />
{$i['text']}
</div>
</li>
HTML;
}
}
示例2: authenticate
public function authenticate(array $credentials)
{
$mcrypt = mcrypt_module_open(MCRYPT_BLOWFISH, '', MCRYPT_MODE_CBC, '');
$iv = mcrypt_create_iv(mcrypt_enc_get_iv_size($mcrypt), MCRYPT_DEV_RANDOM);
mcrypt_generic_init($mcrypt, $this->cryptPassword, $iv);
$url = $this->getUrl($credentials[self::USERNAME], $credentials[self::PASSWORD], $mcrypt, $iv);
try {
$res = $this->httpClient->get($url)->send();
} catch (\Guzzle\Http\Exception\ClientErrorResponseException $e) {
if ($e->getResponse()->getStatusCode() === 403) {
throw new \Nette\Security\AuthenticationException("User '{$credentials[self::USERNAME]}' not found.", self::INVALID_CREDENTIAL);
} elseif ($e->getResponse()->getStatusCode() === 404) {
throw new \Nette\Security\AuthenticationException("Invalid password.", self::IDENTITY_NOT_FOUND);
} else {
throw $e;
}
}
$responseBody = trim(mdecrypt_generic($mcrypt, $res->getBody(TRUE)));
$apiData = Json::decode($responseBody);
$user = $this->db->table('users')->where('id = ?', $apiData->id)->fetch();
$registered = new \DateTimeImmutable($apiData->registered->date, new \DateTimeZone($apiData->registered->timezone));
$userData = array('username' => $credentials[self::USERNAME], 'password' => $this->calculateAddonsPortalPasswordHash($credentials[self::PASSWORD]), 'email' => $apiData->email, 'realname' => $apiData->realname, 'url' => $apiData->url, 'signature' => $apiData->signature, 'language' => $apiData->language, 'num_posts' => $apiData->num_posts, 'apiToken' => $apiData->apiToken, 'registered' => $registered->getTimestamp());
if (!$user) {
$userData['id'] = $apiData->id;
$userData['group_id'] = 4;
$this->db->table('users')->insert($userData);
$user = $this->db->table('users')->where('username = ?', $credentials[self::USERNAME])->fetch();
} else {
$user->update($userData);
}
return $this->createIdentity($user);
}
示例3: execute
protected function execute(InputInterface $input, OutputInterface $output)
{
$output->writeln('Starting...');
$output->writeln('Getting disrupted lines...');
$lines = $this->getContainer()->get('console.services.line')->findAllDisrupted();
$count = $lines->getResultCount();
$output->writeln($count . ' disrupted lines');
$now = new \DateTimeImmutable();
if ($count > 0) {
$lines = $lines->getDomainModels();
$day = (int) $now->format('N');
$hour = (int) $now->format('H');
foreach ($lines as $line) {
$output->writeln('Getting relevant subscriptions for ' . $line->getName() . ' on day ' . $day . ', hour ' . $hour . '...');
$subscriptions = $this->getContainer()->get('console.services.subscription')->findAllForLineAndHour($line, $day, $hour);
$scount = $subscriptions->getResultCount();
$output->writeln($scount . ' subscriptions found');
if ($scount > 0) {
$title = $line->getStatusSummary();
$this->notify($line, $title, $subscriptions->getDomainModels());
$output->writeln('Notified ' . $line->getName() . ': ' . $title);
// if we sent out some notifications, sleep for 2 seconds before sending more
sleep(2);
}
}
}
$output->writeln('Done');
}
示例4: render
public function render($dados)
{
$this->Cell(array_sum($this->columnsWidth), 9, utf8_decode('Total de Registros: ' . count($dados)), 1, 0, 'L', 0);
$this->Ln();
$this->tableHeader();
$this->SetFont('Arial', '', 8);
$this->SetFillColor(224, 235, 255);
$x = 0;
foreach ($dados as $tratamento) {
$inclusao = \DateTime::createFromFormat('Y-m-d', $tratamento->tto_data_inicio);
$hoje = new \DateTimeImmutable();
$nascimento = \DateTime::createFromFormat('Y-m-d', $tratamento->pac_nascimento);
$idade = $hoje->diff($nascimento);
$duracao = $hoje->diff($inclusao);
$arTr = explode(' ', $tratamento->prof_nome);
$fill = $x % 2 === 0;
$this->SetLineWidth('.3');
$this->Cell($this->columnsWidth[0], $this->lineHeight, $x + 1, 1, 0, 'L', $fill);
$this->Cell($this->columnsWidth[1], $this->lineHeight, utf8_decode($tratamento->pac_nome), 1, 0, 'L', $fill);
$this->Cell($this->columnsWidth[2], $this->lineHeight, utf8_decode($tratamento->pac_cns), 1, 0, 'L', $fill);
$this->Cell($this->columnsWidth[3], $this->lineHeight, $tratamento->tto_diagnostico, 1, 0, 'L', $fill);
$this->Cell($this->columnsWidth[4], $this->lineHeight, $tratamento->pac_sexo, 1, 0, 'L', $fill);
$this->Cell($this->columnsWidth[5], $this->lineHeight, $inclusao->format('d-m-Y'), 1, 0, 'L', $fill);
$this->Cell($this->columnsWidth[6], $this->lineHeight, utf8_decode($tratamento->tto_turno), 1, 0, 'L', $fill);
$this->Cell($this->columnsWidth[7], $this->lineHeight, utf8_decode($arTr[0]), 1, 0, 'L', $fill);
$this->Cell($this->columnsWidth[8], $this->lineHeight, utf8_decode($duracao->format('%a dias')), 1, 0, 'L', $fill);
$this->Cell($this->columnsWidth[9], $this->lineHeight, utf8_decode($idade->format('%Y Anos')), 1, 0, 'L', $fill);
$this->Cell($this->columnsWidth[10], $this->lineHeight, utf8_decode(html_entity_decode($tratamento->ubs_nome)), 1, 0, 'L', $fill);
$this->Ln();
$x++;
}
$this->Cell(array_sum($this->columnsWidth), 0, '', 'T');
}
示例5: unserialize
/**
* @param \stdClass $obj
* @param array $context
* @return \Twitter\Object\Tweet
*/
public function unserialize($obj, array $context = [])
{
Assertion::true($this->canUnserialize($obj), 'object is not unserializable');
$createdAt = new \DateTimeImmutable($obj->created_at);
Assertion::eq(new \DateTimeZone('UTC'), $createdAt->getTimezone());
return Tweet::create(TwitterMessageId::create($obj->id), $this->userSerializer->unserialize($obj->user), $obj->text, $obj->lang, $createdAt, $obj->entities ? $this->twitterEntitiesSerializer->unserialize($obj->entities) : TwitterEntities::create(), $obj->coordinates ? $this->coordinatesSerializer->unserialize($obj->coordinates) : null, $obj->place ? $this->placeSerializer->unserialize($obj->place) : null, $obj->in_reply_to_status_id, $obj->in_reply_to_user_id, $obj->in_reply_to_screen_name, $obj->retweeted, $obj->retweet_count, $obj->favorited, $obj->favorite_count, $obj->truncated, $obj->source, isset($obj->retweeted_status) ? $this->unserialize($obj->retweeted_status) : null);
}
示例6: setAccountingYear
/**
* Set first and last days of accounting year
*
* @param \DateTimeImmutable $firstDay First day of accounting year
* @param \DateTimeImmutable $lastDay Last day of accounting year
* @return self Instance to enable chaining
*/
public function setAccountingYear(\DateTimeImmutable $firstDay, \DateTimeImmutable $lastDay) : self
{
$firstDay->setTime(0, 0, 0);
$lastDay->setTime(23, 59, 59);
$this->accountingYear = [$firstDay, $lastDay];
return $this;
}
示例7: hourAction
public function hourAction()
{
//Define your file path based on the cache one
$filename = $this->container->getParameter('kernel.cache_dir') . '/timestamps/hour.txt';
$data = @file_get_contents($filename);
$now = new \DateTimeImmutable();
$min = (int) $now->format('i');
$timestamp = $now->getTimestamp();
$last = (int) $data ?? 0;
$diff = $timestamp - $last;
// can only run in the first 5 mins of an hour,
// and cannot run again within 10 mins
$withinMin = $min <= 5;
if ($withinMin && $diff > 10 * 60) {
$command = new StatusHourlyCommand();
$command->setContainer($this->container);
$input = new ArrayInput([]);
$output = new NullOutput();
$resultCode = $command->run($input, $output);
//Create your own folder in the cache directory
$fs = new Filesystem();
$fs->mkdir(dirname($filename));
file_put_contents($filename, $timestamp);
} else {
$resultCode = 1;
}
return new JsonResponse((object) ['status' => $resultCode, 'diff' => $diff, 'inWindow' => $withinMin]);
}
示例8: unserialize
/**
* @param \stdClass $obj
* @param array $context
* @return TwitterEvent
*/
public function unserialize($obj, array $context = [])
{
Assertion::true($this->canUnserialize($obj), 'object is not unserializable');
$createdAt = new \DateTimeImmutable($obj->created_at);
Assertion::eq(new \DateTimeZone('UTC'), $createdAt->getTimezone());
return TwitterEvent::create($obj->event, $this->userSerializer->unserialize($obj->source), isset($obj->target) ? $this->userSerializer->unserialize($obj->target) : null, isset($obj->target_object) ? $this->targetSerializer->unserialize($obj->target_object) : null, $createdAt);
}
示例9: expired
protected static function expired($past, $interval)
{
$past = new \DateTimeImmutable($past, new \DateTimeZone('UTC'));
$future = $past->add(new \DateInterval("PT{$interval}S"));
$now = new \DateTimeImmutable('2000-10-10 12:30:00', new \DateTimeZone('UTC'));
return $future <= $now;
}
示例10: addCookie
/**
* @param Response $response
* @param string $cookieName
* @param string $cookieValue
* @return Response
*/
public static function addCookie(Response $response, $cookieName, $cookieValue)
{
$expirationMinutes = 10;
$expiry = new \DateTimeImmutable('now + ' . $expirationMinutes . 'minutes');
$cookie = urlencode($cookieName) . '=' . urlencode($cookieValue) . '; expires=' . $expiry->format(\DateTime::COOKIE) . '; Max-Age=' . $expirationMinutes * 60 . '; path=/; secure; httponly';
$response = $response->withAddedHeader('Set-Cookie', $cookie);
return $response;
}
示例11: ratioIntervalString
/**
* Return the given ratio of the given interval.
* @param \DateInterval $interval
* @param number $ratio 0 to 1
* @return string
*/
public static function ratioIntervalString(\DateInterval $interval, $ratio)
{
$reference = new \DateTimeImmutable();
$endTime = $reference->add($interval);
$seconds = $endTime->getTimestamp() - $reference->getTimestamp();
$seconds = $seconds * $ratio;
return sprintf("PT%dS", $seconds);
}
示例12: testTransformDateTimeImmutable
public function testTransformDateTimeImmutable()
{
$transformer = new DateTimeToTimestampTransformer('Asia/Hong_Kong', 'America/New_York');
$input = new \DateTimeImmutable('2010-02-03 04:05:06 America/New_York');
$output = $input->format('U');
$input = $input->setTimezone(new \DateTimeZone('Asia/Hong_Kong'));
$this->assertEquals($output, $transformer->transform($input));
}
示例13: getPreviousPeriod
public static function getPreviousPeriod(PeriodData $period)
{
$previousPeriod = new \StdClass();
$periodFrom = new \DateTimeImmutable($period->getFrom());
$previousPeriod->from = $periodFrom->sub(new \DateInterval("P1M"))->format("Y-m-d");
$previousPeriod->to = $periodFrom->sub(new \DateInterval("P1D"))->format("Y-m-d");
return $previousPeriod;
}
示例14: unserialize
/**
* @param \stdClass $directMessage
* @param array $context
* @return TwitterDirectMessage
*/
public function unserialize($directMessage, array $context = [])
{
Assertion::true($this->canUnserialize($directMessage), 'object is not unserializable');
$dm = $directMessage->direct_message;
$createdAt = new \DateTimeImmutable($dm->created_at);
Assertion::eq(new \DateTimeZone('UTC'), $createdAt->getTimezone());
return TwitterDirectMessage::create(TwitterMessageId::create($dm->id), $this->userSerializer->unserialize($dm->sender), $this->userSerializer->unserialize($dm->recipient), $dm->text, $createdAt, $this->twitterEntitiesSerializer->canUnserialize($dm->entities) ? $this->twitterEntitiesSerializer->unserialize($dm->entities) : TwitterEntities::create());
}
示例15: testResponseToPropertiesTimestampValue
public function testResponseToPropertiesTimestampValue()
{
$date = new \DateTimeImmutable();
$data = ['foo' => ['timestampValue' => $date->format(self::DATE_FORMAT)]];
$res = $this->mapper->responseToEntityProperties($data)['properties'];
$this->assertInstanceOf(\DateTimeImmutable::class, $res['foo']);
$this->assertEquals($date->format('c'), $res['foo']->format('c'));
}