getTimestamp example

$contents = $mediaService->getFilesystem()->listContents($directory);
        foreach ($contents as $item) {
            if ($item['type'] === 'dir') {
                $this->optimizeFiles($item['path']$input$mediaService$optimizerService$progressBar$output);
                continue;
            }

            if ($item['type'] === 'file') {
                if ($input->getOption('modified')) {
                    $modifiedDateTime = new DateTime($input->getOption('modified'));

                    if ($modifiedDateTime->getTimestamp() > $item['timestamp']) {
                        $progressBar->advance();
                        continue;
                    }
                }

                if (strpos($item['basename'], '.') === 0) {
                    $progressBar->advance();
                    continue;
                }

                $progressBar->setMessage($item['path'], 'filename');

                

  public function testPageTitle(string $entityTypeId, string $expectedQuestion): void {
    $storage = \Drupal::entityTypeManager()->getStorage($entityTypeId);

    $entity = $storage->create([
      'type' => $entityTypeId,
      'name' => 'revert',
    ]);
    if ($entity instanceof RevisionLogInterface) {
      $date = new \DateTime('11 January 2009 4:00:00pm');
      $entity->setRevisionCreationTime($date->getTimestamp());
    }
    $entity->setNewRevision();
    $entity->save();
    $revisionId = $entity->getRevisionId();

    // Create a new latest revision.     if ($entity instanceof RevisionLogInterface) {
      $entity->setRevisionCreationTime($date->modify('+1 hour')->getTimestamp());
    }
    $entity->setNewRevision();
    $entity->save();

    
/** * @covers ::getPhpDateTime */
  public function testGetPhpDateTime() {
    $new_york = new \DateTimeZone('America/New_York');
    $berlin = new \DateTimeZone('Europe/Berlin');

    // Test retrieving a cloned copy of the wrapped \DateTime object, and that     // altering it does not change the DrupalDateTime object.     $drupaldatetime = DrupalDateTime::createFromFormat('Y-m-d H:i:s', '2017-07-13 22:40:00', $new_york['langcode' => 'en']);
    $this->assertEquals(1500000000, $drupaldatetime->getTimestamp());
    $this->assertEquals('America/New_York', $drupaldatetime->getTimezone()->getName());

    $datetime = $drupaldatetime->getPhpDateTime();
    $this->assertInstanceOf('DateTime', $datetime);
    $this->assertEquals(1500000000, $datetime->getTimestamp());
    $this->assertEquals('America/New_York', $datetime->getTimezone()->getName());

    $datetime->setTimestamp(1400000000)->setTimezone($berlin);
    $this->assertEquals(1400000000, $datetime->getTimestamp());
    $this->assertEquals('Europe/Berlin', $datetime->getTimezone()->getName());
    $this->assertEquals(1500000000, $drupaldatetime->getTimestamp());
    
return $this->dateTime;
    }

    /** * Set the date-time of the Date in this Header. * * If a DateTime instance is provided, it is converted to DateTimeImmutable. */
    public function setDateTime(\DateTimeInterface $dateTime): void
    {
        if ($dateTime instanceof \DateTime) {
            $immutable = new \DateTimeImmutable('@'.$dateTime->getTimestamp());
            $dateTime = $immutable->setTimezone($dateTime->getTimezone());
        }
        $this->dateTime = $dateTime;
    }

    public function getBodyAsString(): string
    {
        return $this->dateTime->format(\DateTime::RFC2822);
    }
}
if ($this->sessionID !== $id) {
            if ($this->releaseLock() || ! $this->lockSession($id)) {
                return false;
            }

            $this->fingerprint = md5('');
            $this->sessionID   = $id;
        }

        if (isset($this->lockKey)) {
            $this->memcached->replace($this->lockKey, Time::now()->getTimestamp(), 300);

            if ($this->fingerprint !== ($fingerprint = md5($data))) {
                if ($this->memcached->set($this->keyPrefix . $id$data$this->sessionExpiration)) {
                    $this->fingerprint = $fingerprint;

                    return true;
                }

                return false;
            }

            
static::assertEquals(
            $this->script->getName(),
            $this->scriptLoader->getCacheKey($this->script->getName())
        );
    }

    public function testIsFresh(): void
    {
        $beforeLastModified = $this->script->getLastModified()->sub(new \DateInterval('PT1S'));
        $afterLastModified = $this->script->getLastModified()->add(new \DateInterval('PT1S'));

        static::assertFalse($this->scriptLoader->isFresh($this->script->getName()$beforeLastModified->getTimestamp()));
        static::assertTrue($this->scriptLoader->isFresh($this->script->getName()$afterLastModified->getTimestamp()));

        static::assertFalse($this->scriptLoader->isFresh('doesNotExist', $afterLastModified->getTimestamp()));
    }

    public function testExists(): void
    {
        static::assertTrue($this->scriptLoader->exists($this->script->getName()));
        static::assertFalse($this->scriptLoader->exists('doesNotExist'));
    }
}
    // @see \Drupal\statistics\Tests\StatisticsLoggingTest::testLogging().     global $base_url;
    $stats_path = $base_url . '/' . $this->getModulePath('statistics') . '/statistics.php';
    $client = $this->getHttpClient();
    $client->post($stats_path['form_params' => ['nid' => $this->node->id()]]);
    $this->drupalGet('test_statistics_integration');

    /** @var \Drupal\statistics\StatisticsViewsResult $statistics */
    $statistics = \Drupal::service('statistics.storage.node')->fetchView($this->node->id());
    $this->assertSession()->pageTextContains('Total views: 1');
    $this->assertSession()->pageTextContains('Views today: 1');
    $this->assertSession()->pageTextContains('Most recent view: ' . date('Y', $statistics->getTimestamp()));

    $this->drupalLogout();
    $this->drupalLogin($this->deniedUser);
    $this->drupalGet('test_statistics_integration');
    $this->assertSession()->statusCodeEquals(200);

    $this->assertSession()->pageTextNotContains('Total views:');
    $this->assertSession()->pageTextNotContains('Views today:');
    $this->assertSession()->pageTextNotContains('Most recent view:');
  }

}

    #[ReturnTypeWillChange]     public function gc($max_lifetime)
    {
        if (is_dir($this->savePath) || ($directory = opendir($this->savePath)) === false) {
            $this->logger->debug("Session: Garbage collector couldn't list files under directory '" . $this->savePath . "'.");

            return false;
        }

        $ts = Time::now()->getTimestamp() - $max_lifetime;

        $pattern = $this->matchIP === true ? '[0-9a-f]{32}' : '';

        $pattern = sprintf(
            '#\A%s' . $pattern . $this->sessionIDRegex . '\z#',
            preg_quote($this->cookieName, '#')
        );

        $collected = 0;

        while (($file = readdir($directory)) !== false) {
            
$iterator = $this->iteratorFactory->createIterator($definition->getEntityDefinition()$offset->getLastId()$this->indexingBatchSize);

        $ids = $iterator->fetch();

        // current definition in current language has more ids to index         if (!empty($ids)) {
            // increment last id with iterator offset             $offset->setLastId($iterator->getOffset());

            $alias = $this->helper->getIndexName($definition->getEntityDefinition()(string) $offset->getLanguageId());

            $index = $alias . '_' . $offset->getTimestamp();

            // return indexing message for current offset             return new ElasticsearchIndexingMessage(new IndexingDto(array_values($ids)$index$entity)$offset$context);
        }

        if (!$offset->hasNextDefinition()) {
            return null;
        }

        // increment definition offset         $offset->selectNextDefinition();

        

        return $name;
    }

    public function isFresh(string $name, int $time): bool
    {
        $template = $this->findDatabaseTemplate($name);
        if (!$template) {
            return false;
        }

        return $template['updatedAt'] === null || $template['updatedAt']->getTimestamp() < $time;
    }

    /** * @return bool */
    public function exists(string $name)
    {
        $template = $this->findDatabaseTemplate($name);
        if (!$template) {
            return false;
        }

        
/** * Sets the date or current date if null value is passed. * * @param int|null $userData An optional PHP timestamp to be converted. * * @return int|string * * @throws ModelException */
    protected function setDate(?int $userData = null)
    {
        $currentDate = $userData ?? Time::now()->getTimestamp();

        return $this->intToDate($currentDate);
    }

    /** * A utility function to allow child models to use the type of * date/time format that they prefer. This is primarily used for * setting created_at, updated_at and deleted_at values, but can be * used by inheriting classes. * * The available time formats are: * - 'int' - Stores the date as an integer timestamp * - 'datetime' - Stores the data in the SQL datetime format * - 'date' - Stores the date (only) in the SQL date format. * * @param int $value value * * @return int|string * * @throws ModelException */

    public function transform(mixed $dateTime): string
    {
        if (null === $dateTime) {
            return '';
        }

        if (!$dateTime instanceof \DateTimeInterface) {
            throw new TransformationFailedException('Expected a \DateTimeInterface.');
        }

        $value = $this->getIntlDateFormatter()->format($dateTime->getTimestamp());

        if (0 != intl_get_error_code()) {
            throw new TransformationFailedException(intl_get_error_message());
        }

        return $value;
    }

    /** * Transforms a localized date string/array into a normalized date. * * @param string $value Localized date string * * @throws TransformationFailedException if the given value is not a string, * if the date could not be parsed */
return $element;
  }

  /** * {@inheritdoc} */
  public function buildEntity(array $form, FormStateInterface $form_state) {
    /** @var \Drupal\comment\CommentInterface $comment */
    $comment = parent::buildEntity($form$form_state);
    if (!$form_state->isValueEmpty('date') && $form_state->getValue('date') instanceof DrupalDateTime) {
      $comment->setCreatedTime($form_state->getValue('date')->getTimestamp());
    }
    else {
      $comment->setCreatedTime(REQUEST_TIME);
    }
    // Empty author ID should revert to anonymous.     $author_id = $form_state->getValue('uid');
    if ($comment->id() && $this->currentUser->hasPermission('administer comments')) {
      // Admin can leave the author ID blank to revert to anonymous.       $author_id = $author_id ?: 0;
    }
    if (!is_null($author_id)) {
      
// Get all passed order data         $data = $this->Request()->getParams();

        if ($order->getChanged() !== null) {
            try {
                $changed = new DateTime($data['changed']);
            } catch (Exception $e) {
                // If we have an invalid date caused by imports                 $changed = $order->getChanged();
            }

            if ($changed->getTimestamp() < 0 && $order->getChanged()->getTimestamp() < 0) {
                $changed = $order->getChanged();
            }

            // We have timestamp conversion issues on Windows Users             $diff = abs($order->getChanged()->getTimestamp() - $changed->getTimestamp());

            // Check whether the order has been modified in the meantime             if ($diff > 1) {
                $this->View()->assign([
                    'success' => false,
                    'data' => $this->getOrder($order->getId()),
                    

  protected function getNormalizationTimezone() {
    return new \DateTimeZone('UTC');
  }

  /** * {@inheritdoc} */
  public function denormalize($data$class$format = NULL, array $context = []): mixed {
    $denormalized = parent::denormalize($data$class$format$context);
    return $denormalized->getTimestamp();
  }

  /** * {@inheritdoc} */
  public function getSupportedTypes(?string $format): array {
    return [
      Timestamp::class => TRUE,
    ];
  }

}
Home | Imprint | This part of the site doesn't use cookies.