本文整理汇总了PHP中DateTimeImmutable::getTimestamp方法的典型用法代码示例。如果您正苦于以下问题:PHP DateTimeImmutable::getTimestamp方法的具体用法?PHP DateTimeImmutable::getTimestamp怎么用?PHP DateTimeImmutable::getTimestamp使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类DateTimeImmutable
的用法示例。
在下文中一共展示了DateTimeImmutable::getTimestamp方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。
示例1: 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]);
}
示例2: getEpisodesForWeek
/**
* Get all the episodes for the current week.
*/
protected function getEpisodesForWeek(\DateTimeImmutable $start, \DateTimeImmutable $end)
{
$sorted_results = [];
foreach ($this->getAllSeriesEpisodes() as $serie_imdb => $info) {
/** @var \Moinax\TvDb\Episode $episode */
foreach (array_reverse($info['episodes']) as $episode) {
// If we don't have a timestamp we don't know what to do.
if (!$episode->firstAired) {
continue;
}
// Add a day to allow for the US delay.
$episode->firstAired->add(new \DateInterval('P1D'));
// We're going backwards so if we have a timestamp that is before the
// start of our week then we don't have an episode.
if ($episode->firstAired->getTimestamp() < $start->getTimestamp()) {
break;
}
// If the episode falls within our week then we're good.
$episode_timestamp = $episode->firstAired->getTimestamp();
if ($episode_timestamp > $start->getTimestamp() && $episode_timestamp < $end->getTimestamp()) {
$day = $episode->firstAired->format('N');
$sorted_results[$day][] = [$info['serie'], $episode];
}
}
}
ksort($sorted_results);
return $sorted_results;
}
示例3: 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);
}
示例4: 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);
}
示例5: fromString
/**
* Initialize instance from date/time string.
*
* @param string $time <code>strtotime</code> compatible time string
* @param string $tz Default timezone
* @throws \RuntimeException
* @return static
*/
public static function fromString($time, $tz = "UTC")
{
try {
$dt = new \DateTimeImmutable($time, self::_createTimeZone($tz));
return new static($dt->getTimestamp());
} catch (\Exception $e) {
throw new \RuntimeException("Failed to create DateTime: " . self::_getLastDateTimeImmutableErrorsStr(), 0, $e);
}
}
示例6: it_publishes_messages
/**
* @test
*/
public function it_publishes_messages()
{
$now = new \DateTimeImmutable('now', new \DateTimeZone('UTC'));
$producer = $this->prophesize(Producer::class);
$producer->publish(['message_name' => 'test-message', 'uuid' => 'ccefedef-85e1-4fd0-b247-ed13d378b050', 'version' => 1, 'payload' => [], 'metadata' => [], 'created_at' => $now->format('Y-m-d\\TH:i:s.u')], 'test-message', Constants::AMQP_NOPARAM, ['app_id' => 'test_app', 'timestamp' => $now->getTimestamp(), 'type' => 'test-message'])->shouldBeCalled();
$message = $this->prophesize(Message::class);
$message->createdAt()->willReturn($now)->shouldBeCalled();
$message->messageName()->willReturn('test-message')->shouldBeCalled();
$messageConverter = $this->prophesize(MessageConverter::class);
$messageConverter->convertToArray($message)->willReturn(['message_name' => 'test-message', 'uuid' => 'ccefedef-85e1-4fd0-b247-ed13d378b050', 'version' => 1, 'payload' => [], 'metadata' => [], 'created_at' => $now])->shouldBeCalled();
$messageProducer = new AmqpMessageProducer($producer->reveal(), $messageConverter->reveal(), 'test_app');
$messageProducer($message->reveal());
}
示例7: setExpires
public function setExpires($expires)
{
if ($expires === NULL) {
$this->expires = NULL;
} else {
if (is_numeric($expires)) {
$expires = new \DateTimeImmutable('@' . $expires);
} elseif ($expires instanceof \DateTimeInterface) {
$expires = new \DateTimeImmutable('@' . $expires->getTimestamp(), $expires->getTimezone());
} else {
$expires = \DateTimeImmutable::createFromFormat(Http::DATE_COOKIE, $expires);
}
$this->expires = $expires->setTimezone(new \DateTimeZone('UTC'));
}
}
示例8: generateRandomDate
protected function generateRandomDate($is_future, $day_of_week)
{
// Generate a random timestamp.
if ($is_future) {
$time = rand(time() + 86400, getrandmax());
} else {
$time = rand(0, time() - 86400);
}
$date = new \DateTimeImmutable($time);
if ($day_of_week) {
$days_diff = 7 - $day_of_week;
$time = $date->getTimestamp() - $days_diff * 86400;
return new \DateTimeImmutable($time);
}
return $date;
}
示例9: getFormattedDateTime
protected function getFormattedDateTime(Episode $episode)
{
if (!$episode->firstAired) {
return 'N/A';
}
$today = new \DateTimeImmutable();
$format = 'red';
// If the episode comes out today, then make it green.
if ($episode->firstAired->format('d/m/y') === $today->format('d/m/y')) {
$format = 'info';
} elseif ($episode->firstAired->getTimestamp() > $today->getTimestamp()) {
// Episode in the future.
$format = 'comment';
}
$date_time = $episode->firstAired->format('D - d/m/Y');
return $format ? "<{$format}>{$date_time}</{$format}>" : $date_time;
}
示例10: it_can_receive_due_scheduled_commands
public function it_can_receive_due_scheduled_commands()
{
$date = new \DateTimeImmutable();
$timestamp = $date->getTimestamp();
$lua = $this->getLua('receive_due_messages');
$this->adapter->evalLua($lua, ['test', 0, $timestamp, SchedulerWorker::DEFAULT_THROTTLE])->shouldBeCalled()->willReturn([['test', 'test', 'test', $timestamp]]);
$commandsWrapper = $this->receiveDueCommands($date);
$commands = $commandsWrapper->getWrappedObject();
\PHPUnit_Framework_Assert::assertArrayHasKey(0, $commands);
\PHPUnit_Framework_Assert::assertArrayNotHasKey(1, $commands);
\PHPUnit_Framework_Assert::assertEquals('test', $commands[0]->getId());
}
示例11: testAsDatetime
public function testAsDatetime()
{
$value = time();
$this->assertSame(date('M j, Y g:i:s A', $value), $this->formatter->asDatetime($value));
$this->assertSame(date('Y/m/d h:i:s A', $value), $this->formatter->asDatetime($value, 'php:Y/m/d h:i:s A'));
$value = new DateTime();
$this->assertSame(date('M j, Y g:i:s A', $value->getTimestamp()), $this->formatter->asDatetime($value));
$this->assertSame(date('Y/m/d h:i:s A', $value->getTimestamp()), $this->formatter->asDatetime($value, 'php:Y/m/d h:i:s A'));
if (version_compare(PHP_VERSION, '5.5.0', '>=')) {
$value = new \DateTimeImmutable();
$this->assertSame(date('M j, Y g:i:s A', $value->getTimestamp()), $this->formatter->asDatetime($value));
$this->assertSame(date('Y/m/d h:i:s A', $value->getTimestamp()), $this->formatter->asDatetime($value, 'php:Y/m/d h:i:s A'));
}
// empty input
$this->assertSame('Jan 1, 1970 12:00:00 AM', $this->formatter->asDatetime(''));
$this->assertSame('Jan 1, 1970 12:00:00 AM', $this->formatter->asDatetime(0));
$this->assertSame('Jan 1, 1970 12:00:00 AM', $this->formatter->asDatetime(false));
// null display
$this->assertSame($this->formatter->nullDisplay, $this->formatter->asDatetime(null));
}
示例12: createFromDateInterval
/**
* Create a TimeValue from a \DateInterval object
*
* @param \DateInterval $interval
* @return TimeValue
*/
public static function createFromDateInterval(\DateInterval $interval)
{
$utc = new \DateTimeZone('UTC');
$start = new \DateTimeImmutable(null, $utc);
$end = $start->add($interval);
return new TimeValue($end->getTimestamp() - $start->getTimestamp(), 's');
}
示例13: updateProperty
public function updateProperty(ResourceInterface $resource, XmlName $prop, \DOMElement $value)
{
if (!$resource instanceof FilesystemResource) {
throw new \InvalidArgumentException(sprintf('Expecting a filesystem resource, given %s', get_class($resource)));
}
if ($prop->getNamespaceUri() == WebDav::NS_DAV) {
switch ($prop->getLocalName()) {
case 'getlastmodified':
$text = trim($value->textContent);
$date = new \DateTimeImmutable(is_numeric($text) ? '@' . $text : $text);
touch($resource->getFileInfo()->getPathname(), $date->getTimestamp());
return;
}
}
if ($prop->getNamespaceUri() == WebDav::NS_WIN32) {
switch ($prop->getLocalName()) {
case 'Win32LastModifiedTime':
$text = trim($value->textContent);
$date = new \DateTimeImmutable(is_numeric($text) ? '@' . $text : $text);
touch($resource->getFileInfo()->getPathname(), $date->getTimestamp());
return;
}
}
return parent::updateProperty($resource, $prop, $value);
}
示例14: getTimestampInterval
/**
* Returns the PeriodLib duration as expressed in seconds
*
* @return float
*/
public function getTimestampInterval()
{
$end = $this->endDate->getTimestamp() + (int) $this->endDate->format('u') * 1.0E-6;
$start = $this->startDate->getTimestamp() + (int) $this->startDate->format('u') * 1.0E-6;
return (double) sprintf('%f', $end - $start);
}
示例15: canEditEvent
public static function canEditEvent(self $event, User $user)
{
$now = new \DateTimeImmutable();
if ($event->start->getTimestamp() < $now->getTimestamp()) {
// Too Old
return false;
}
$isCouncil = $user->rank >= User::RANK_LIEUTENANT;
$isLeader = is_null($event->leader) ? false : $event->leader->id == $user->id;
return $isCouncil || $isLeader;
}