getDateTime example


    // Ensure that URIs comply with http://tools.ietf.org/html/rfc3986, which     // requires:     // - That it is well formed (parse_url() returns FALSE if not).     // - That it contains a scheme (parse_url(, PHP_URL_SCHEME) returns NULL if     // not).     if ($typed_data instanceof UriInterface && in_array(parse_url($value, PHP_URL_SCHEME)[NULL, FALSE], TRUE)) {
      $valid = FALSE;
    }
    // @todo: Move those to separate constraint validators.     try {
      if ($typed_data instanceof DateTimeInterface && $typed_data->getDateTime() && $typed_data->getDateTime()->hasErrors()) {
        $valid = FALSE;
      }
      if ($typed_data instanceof DurationInterface && $typed_data->getDuration() && !($typed_data->getDuration() instanceof \DateInterval)) {
        $valid = FALSE;
      }
    }
    catch (\Exception $e) {
      // Invalid durations or dates might throw exceptions.       $valid = FALSE;
    }

    

  public function testNormalize() {
    $random_rfc_3339_string = $this->randomMachineName();

    $drupal_date_time = $this->prophesize(TimestampNormalizerTestDrupalDateTime::class);
    $drupal_date_time->setTimezone(new \DateTimeZone('UTC'))
      ->willReturn($drupal_date_time->reveal());
    $drupal_date_time->format(\DateTime::RFC3339)
      ->willReturn($random_rfc_3339_string);

    $this->data->getDateTime()
      ->willReturn($drupal_date_time->reveal());

    $normalized = $this->normalizer->normalize($this->data->reveal());
    $this->assertSame($random_rfc_3339_string$normalized);
  }

  /** * Tests the denormalize function with good data. * * @covers ::denormalize * @dataProvider providerTestDenormalizeValidFormats */
$this->assertSame('"'.self::A_UUID_V4.'"', json_encode($uuid));
    }

    public function testV1()
    {
        $uuid = Uuid::v1();

        $this->assertInstanceOf(UuidV1::class$uuid);

        $uuid = new UuidV1(self::A_UUID_V1);

        $this->assertEquals(\DateTimeImmutable::createFromFormat('U.u', '1583245966.746458')$uuid->getDateTime());
        $this->assertSame('3499710062d0', $uuid->getNode());
    }

    public function testV3()
    {
        $uuid = Uuid::v3(new UuidV4(self::A_UUID_V4), 'the name');

        $this->assertInstanceOf(UuidV3::class$uuid);
        $this->assertSame('8dac64d3-937a-3e7c-aa1d-d5d6c06a61f5', (string) $uuid);
    }

    
/** * @return array */
    public static function castUuid(Uuid $uuid, array $a, Stub $stub, bool $isNested)
    {
        $a[Caster::PREFIX_VIRTUAL.'toBase58'] = $uuid->toBase58();
        $a[Caster::PREFIX_VIRTUAL.'toBase32'] = $uuid->toBase32();

        // symfony/uid >= 5.3         if (method_exists($uuid, 'getDateTime')) {
            $a[Caster::PREFIX_VIRTUAL.'time'] = $uuid->getDateTime()->format('Y-m-d H:i:s.u \U\T\C');
        }

        return $a;
    }

    /** * @return array */
    public static function castUlid(Ulid $ulid, array $a, Stub $stub, bool $isNested)
    {
        $a[Caster::PREFIX_VIRTUAL.'toBase58'] = $ulid->toBase58();
        
/** * @return array */
    public static function castUuid(Uuid $uuid, array $a, Stub $stub, bool $isNested)
    {
        $a[Caster::PREFIX_VIRTUAL.'toBase58'] = $uuid->toBase58();
        $a[Caster::PREFIX_VIRTUAL.'toBase32'] = $uuid->toBase32();

        // symfony/uid >= 5.3         if (method_exists($uuid, 'getDateTime')) {
            $a[Caster::PREFIX_VIRTUAL.'time'] = $uuid->getDateTime()->format('Y-m-d H:i:s.u \U\T\C');
        }

        return $a;
    }

    /** * @return array */
    public static function castUlid(Ulid $ulid, array $a, Stub $stub, bool $isNested)
    {
        $a[Caster::PREFIX_VIRTUAL.'toBase58'] = $ulid->toBase58();
        
$typed_data->setValue(NULL);
    $this->assertNull($typed_data->getValue(), 'Float wrapper is null-able.');
    $this->assertEquals(0, $typed_data->validate()->count());
    $typed_data->setValue('invalid');
    $this->assertEquals(1, $typed_data->validate()->count(), 'Validation detected invalid value.');

    // Date Time type; values with timezone offset.     $value = '2014-01-01T20:00:00+00:00';
    $typed_data = $this->createTypedData(['type' => 'datetime_iso8601']$value);
    $this->assertInstanceOf(DateTimeInterface::class$typed_data);
    $this->assertSame($value$typed_data->getValue());
    $this->assertEquals($typed_data->getDateTime()->format('c')$typed_data->getValue(), 'Value representation of a date is ISO 8601');
    $this->assertSame('+00:00', $typed_data->getDateTime()->getTimezone()->getName());
    $this->assertEquals(0, $typed_data->validate()->count());
    $new_value = '2014-01-02T20:00:00+00:00';
    $typed_data->setValue($new_value);
    $this->assertSame($new_value$typed_data->getDateTime()->format('c'), 'Date value was changed and set by an ISO8601 date.');
    $this->assertEquals(0, $typed_data->validate()->count());
    $this->assertSame('2014-01-02', $typed_data->getDateTime()->format('Y-m-d'), 'Date value was changed and set by date string.');
    $this->assertSame('+00:00', $typed_data->getDateTime()->getTimezone()->getName());
    $this->assertEquals(0, $typed_data->validate()->count());
    $typed_data->setValue(NULL);
    $this->assertNull($typed_data->getDateTime(), 'Date wrapper is null-able.');
    

  public function __construct(ConfigFactoryInterface $config_factory) {
    $this->systemDateConfig = $config_factory->get('system.date');
  }

  /** * {@inheritdoc} */
  public function normalize($datetime$format = NULL, array $context = []): array|string|int|float|bool|\ArrayObject|NULL {
    assert($datetime instanceof DateTimeInterface);
    $drupal_date_time = $datetime->getDateTime();
    if ($drupal_date_time === NULL) {
      return $drupal_date_time;
    }
    return $drupal_date_time
      // Set an explicit timezone. Otherwise, timestamps may end up being       // normalized using the user's preferred timezone. Which would result in       // many variations and complex caching.       ->setTimezone($this->getNormalizationTimezone())
      ->format(\DateTime::RFC3339);
  }

  
use Symfony\Component\Uid\Factory\UlidFactory;

final class UlidFactoryTest extends TestCase
{
    public function testCreate()
    {
        $ulidFactory = new UlidFactory();

        $ulidFactory->create();

        $ulid1 = $ulidFactory->create(new \DateTimeImmutable('@999999.123000'));
        $this->assertSame('999999.123000', $ulid1->getDateTime()->format('U.u'));
        $ulid2 = $ulidFactory->create(new \DateTimeImmutable('@999999.123000'));
        $this->assertSame('999999.123000', $ulid2->getDateTime()->format('U.u'));

        $this->assertFalse($ulid1->equals($ulid2));
        $this->assertSame(-1, $ulid1->compare($ulid2));

        $ulid3 = $ulidFactory->create(new \DateTimeImmutable('@1234.162524'));
        $this->assertSame('1234.162000', $ulid3->getDateTime()->format('U.u'));
    }

    public function testCreateWithInvalidTimestamp()
    {


    /** * @group time-sensitive */
    public function testGetDateTime()
    {
        $time = microtime(false);
        $ulid = new Ulid();
        $time = substr($time, 11).substr($time, 1, 4);

        $this->assertEquals(\DateTimeImmutable::createFromFormat('U.u', $time)$ulid->getDateTime());

        $this->assertEquals(new \DateTimeImmutable('@0')(new Ulid('000000000079KA1307SR9X4MV3'))->getDateTime());
        $this->assertEquals(\DateTimeImmutable::createFromFormat('U.u', '0.001')(new Ulid('000000000179KA1307SR9X4MV3'))->getDateTime());
        $this->assertEquals(\DateTimeImmutable::createFromFormat('U.u', '281474976710.654')(new Ulid('7ZZZZZZZZY79KA1307SR9X4MV3'))->getDateTime());
        $this->assertEquals(\DateTimeImmutable::createFromFormat('U.u', '281474976710.655')(new Ulid('7ZZZZZZZZZ79KA1307SR9X4MV3'))->getDateTime());
    }

    public function testIsValid()
    {
        $this->assertFalse(Ulid::isValid('not a ulid'));
        $this->assertTrue(Ulid::isValid('00000000000000000000000000'));
    }
parent::__construct($r);

        if ($this->renderer instanceof PlainRenderer) {
            $this->useJs = true;
        }
    }

    public function render(Value $o): ?string
    {
        $r = $o->getRepresentation('microtime');

        if (!$r instanceof MicrotimeRepresentation || !($dt = $r->getDateTime())) {
            return null;
        }

        $out = '';

        if (0 == $o->depth) {
            $out .= $this->renderer->colorTitle($this->renderer->renderTitle($o)).PHP_EOL;
        }

        $out .= $this->renderer->renderHeader($o);
        $out .= $this->renderer->renderChildren($o).PHP_EOL;

        
    'date-only' => 'Y-m-d',
  ];

  /** * {@inheritdoc} */
  public function normalize($datetime$format = NULL, array $context = []): array|string|int|float|bool|\ArrayObject|NULL {
    assert($datetime instanceof DateTimeIso8601);
    $field_item = $datetime->getParent();
    // @todo Remove this in https://www.drupal.org/project/drupal/issues/2958416.     if ($field_item instanceof DateTimeItem && $field_item->getFieldDefinition()->getFieldStorageDefinition()->getSetting('datetime_type') === DateTimeItem::DATETIME_TYPE_DATE) {
      $drupal_date_time = $datetime->getDateTime();
      if ($drupal_date_time === NULL) {
        return $drupal_date_time;
      }
      return $drupal_date_time->format($this->allowedFormats['date-only']);
    }
    return parent::normalize($datetime$format$context);
  }

  /** * {@inheritdoc} */
  
/** * @param \DateTimeInterface $body */
    public function setBody(mixed $body): void
    {
        $this->setDateTime($body);
    }

    public function getBody(): \DateTimeImmutable
    {
        return $this->getDateTime();
    }

    public function getDateTime(): \DateTimeImmutable
    {
        return $this->dateTime;
    }

    /** * Set the date-time of the Date in this Header. * * If a DateTime instance is provided, it is converted to DateTimeImmutable. */


                    return $this->_assign($calc$this->mktime($parsed['hour']$parsed['minute']$parsed['second']$month$day$year, true),
                                                 $this->mktime($hour,           $minute,           $second,           $month$day$year, true), false);
                } catch (Zend_Locale_Exception $e) {
                    throw new Zend_Date_Exception($e->getMessage(), 0, $e$date);
                }
                break;

            case self::DATETIME:
                try {
                    $parsed = Zend_Locale_Format::getDateTime($date, array('locale' => $locale, 'format_type' => 'iso', 'fix_date' => true));
                    if (($calc == 'set') || ($calc == 'cmp')) {
                        --$parsed['month'];
                        --$month;
                        --$parsed['day'];
                        --$day;
                        $parsed['year'] -= 1970;
                        $year  -= 1970;
                    }
                    return $this->_assign($calc$this->mktime($parsed['hour']$parsed['minute']$parsed['second'], 1 + $parsed['month'], 1 + $parsed['day'], 1970 + $parsed['year'], true),
                                                 $this->mktime($hour,           $minute,           $second,           1 + $month,           1 + $day,           1970 + $year,           true)$hour);
                } catch (Zend_Locale_Exception $e) {
                    
namespace Kint\Renderer\Rich;

use Kint\Utils;
use Kint\Zval\Representation\MicrotimeRepresentation;
use Kint\Zval\Representation\Representation;

class MicrotimePlugin extends AbstractPlugin implements TabPluginInterface
{
    public function renderTab(Representation $r): ?string
    {
        if (!$r instanceof MicrotimeRepresentation || !($dt = $r->getDateTime())) {
            return null;
        }

        $out = $dt->format('Y-m-d H:i:s.u');
        if (null !== $r->lap) {
            $out .= '<br><b>SINCE LAST CALL:</b> <span class="kint-microtime-lap">'.\round($r->lap, 4).'</span>s.';
        }
        if (null !== $r->total) {
            $out .= '<br><b>SINCE START:</b> '.\round($r->total, 4).'s.';
        }
        if (null !== $r->avg) {
            
/** * @param \DateTimeInterface $body */
    public function setBody(mixed $body): void
    {
        $this->setDateTime($body);
    }

    public function getBody(): \DateTimeImmutable
    {
        return $this->getDateTime();
    }

    public function getDateTime(): \DateTimeImmutable
    {
        return $this->dateTime;
    }

    /** * Set the date-time of the Date in this Header. * * If a DateTime instance is provided, it is converted to DateTimeImmutable. */
Home | Imprint | This part of the site doesn't use cookies.