### Install Project Dependencies Source: https://github.com/brick/date-time/blob/main/README.md Installs all necessary dependencies for the project using Composer. ```sh composer install ``` -------------------------------- ### Install PHPStan for Static Analysis Source: https://github.com/brick/date-time/blob/main/README.md Installs PHPStan, a static analysis tool, into a dedicated directory. ```sh composer install --working-dir=tools/phpstan ``` -------------------------------- ### PHPUnit Test Setup with DefaultClock Source: https://context7.com/brick/date-time/llms.txt Demonstrates how to use DefaultClock within PHPUnit tests to freeze time during setup and reset it during tearDown for isolated and predictable test execution. ```php // Example: Testing in PHPUnit class MyServiceTest extends TestCase { protected function setUp(): void { // Freeze time for predictable tests DefaultClock::freeze(Instant::of(1718451600)); } protected function tearDown(): void { // Always reset the clock! DefaultClock::reset(); } public function testSubscriptionExpiry(): void { $expiryDate = LocalDate::now(TimeZone::utc())->plusDays(30); // Test logic with predictable dates... } } ``` -------------------------------- ### Install BrickDateTime using Composer Source: https://github.com/brick/date-time/blob/main/README.md Use this command to add the library to your PHP project via Composer. ```bash composer require brick/date-time ``` -------------------------------- ### Install Easy Coding Standard Source: https://github.com/brick/date-time/blob/main/README.md Installs Easy Coding Standard (ECS), a tool for checking and fixing coding style issues, into a dedicated directory. ```sh composer install --working-dir=tools/ecs ``` -------------------------------- ### Install Rector for Automated Refactoring Source: https://github.com/brick/date-time/blob/main/README.md Installs Rector, a tool for automated code refactoring, into a dedicated directory. ```sh composer install --working-dir=tools/rector ``` -------------------------------- ### Get Components of Instant Source: https://context7.com/brick/date-time/llms.txt Retrieve the epoch second and nanosecond components from an Instant object using getEpochSecond() and getNano(). ```php use Brick\DateTime\Instant; // Assuming $instant is already created echo $instant->getEpochSecond(); // 1718451600 echo $instant->getNano(); // 500000000 ``` -------------------------------- ### Get ISO 8601 String Representation of Instant Source: https://context7.com/brick/date-time/llms.txt Get the ISO 8601 string representation of an Instant, including fractional seconds and the 'Z' designator for UTC, using toISOString(). ```php use Brick\DateTime\Instant; // Assuming $instant is already created echo $instant->toISOString(); // "2024-06-15T13:00:00.5Z" ``` -------------------------------- ### Get Date with Fixed Clock in Tests Source: https://github.com/brick/date-time/blob/main/README.md Sets a specific time using FixedClock for testing. The Instant is created from a Unix timestamp. ```php use Brick\DateTime\Clock\FixedClock; use Brick\DateTime\Instant; use Brick\DateTime\LocalDate; use Brick\DateTime\TimeZone; $clock = new FixedClock(Instant::of(1000000000)); echo LocalDate::now(TimeZone::utc(), $clock); // 2001-09-09 ``` -------------------------------- ### Create and Manipulate LocalDate Objects Source: https://context7.com/brick/date-time/llms.txt Demonstrates creating LocalDate objects from year, month, day, or ISO 8601 strings. Includes methods for getting date components, performing arithmetic operations, modifying components, and comparing dates. ```php use Brick\DateTime\LocalDate; use Brick\DateTime\TimeZone; use Brick\DateTime\Month; use Brick\DateTime\DayOfWeek; use Brick\DateTime\Period; // Create a date from year, month, day $date = LocalDate::of(2024, 12, 25); echo $date; // "2024-12-25" // Create from Month enum $date = LocalDate::of(2024, Month::DECEMBER, 25); // Parse from ISO 8601 string $date = LocalDate::parse('2024-06-15'); // Get current date in a time zone $today = LocalDate::now(TimeZone::parse('America/New_York')); // Get date components echo $date->getYear(); // 2024 echo $date->getMonthValue(); // 6 echo $date->getDayOfMonth(); // 15 echo $date->getDayOfWeek(); // DayOfWeek::SATURDAY echo $date->getDayOfYear(); // 167 echo $date->isLeapYear(); // false // Date arithmetic $tomorrow = $date->plusDays(1); $nextWeek = $date->plusWeeks(1); $nextMonth = $date->plusMonths(1); $nextYear = $date->plusYears(1); $yesterday = $date->minusDays(1); // Add a period $period = Period::of(1, 2, 3); // 1 year, 2 months, 3 days $futureDate = $date->plusPeriod($period); // Modify specific components $newDate = $date->withYear(2025)->withMonth(1)->withDay(1); // Date comparisons $date1 = LocalDate::of(2024, 1, 1); $date2 = LocalDate::of(2024, 12, 31); echo $date1->isBefore($date2); // true echo $date1->isAfter($date2); // false echo $date1->isEqualTo($date2); // false // Calculate period between dates $period = $date1->until($date2); echo $period->getMonths(); // 11 echo $period->getDays(); // 30 // Calculate days between dates $days = $date1->daysUntil($date2); // 365 // Find min/max dates $earliest = LocalDate::minOf($date1, $date2, $today); $latest = LocalDate::maxOf($date1, $date2, $today); // Navigate to specific days of week $nextMonday = $date->nextDayOfWeek(DayOfWeek::MONDAY); $prevFriday = $date->previousDayOfWeek(DayOfWeek::FRIDAY); // Convert to native PHP DateTime $nativeDateTime = $date->toNativeDateTime(); $nativeDateTimeImmutable = $date->toNativeDateTimeImmutable(); // Create from native DateTime $date = LocalDate::fromNativeDateTime(new DateTime('2024-06-15')); ``` -------------------------------- ### Get and Modify Period Components Source: https://context7.com/brick/date-time/llms.txt Shows how to retrieve the years, months, and days from a Period object and how to create new periods with modified components using `withYears`, `withMonths`, and `withDays`. ```php // Get components echo $period->getYears(); // 4 echo $period->getMonths(); // 5 echo $period->getDays(); // 5 // Modify components $newPeriod = $period->withYears(10); $newPeriod = $period->withMonths(6); $newPeriod = $period->withDays(15); ``` -------------------------------- ### Get Decimal Representation of Instant Source: https://context7.com/brick/date-time/llms.txt Get the decimal string representation of an Instant, including seconds and fractional seconds, using toDecimal(). ```php use Brick\DateTime\Instant; // Assuming $instant is already created echo $instant->toDecimal(); // "1718451600.5" ``` -------------------------------- ### Get Duration Components Source: https://context7.com/brick/date-time/llms.txt Retrieve the total seconds and nanosecond adjustment from a Duration object. ```php use Brick\DateTime\Duration; // Get components echo $duration->getSeconds(); // total seconds echo $duration->getNanos(); // nanosecond adjustment (0-999999999) ``` -------------------------------- ### Get Current Instant Source: https://context7.com/brick/date-time/llms.txt Obtain the current point in time as an Instant object using Instant::now(). This provides a high-precision, timezone-agnostic timestamp. ```php use Brick\DateTime\Instant; $now = Instant::now(); ``` -------------------------------- ### Get Time Zone ID and Offset Source: https://context7.com/brick/date-time/llms.txt Explains how to retrieve the unique identifier of a time zone using `getId()` and how to determine the offset of a region-based time zone at a specific instant, accounting for Daylight Saving Time. ```php // Get time zone ID echo $tz->getId(); // "America/New_York" or "+05:30" // Get offset at a specific instant (handles DST) $instant = Instant::now(); $offsetSeconds = $region->getOffset($instant); echo $offsetSeconds / 3600; // offset in hours ``` -------------------------------- ### Get LocalTime Components Source: https://context7.com/brick/date-time/llms.txt Extract individual time components such as hour, minute, second, and nanosecond from a LocalTime object. ```php use Brick\DateTime\LocalTime; // Get time components $time = LocalTime::parse('10:15:30'); echo $time->getHour(); // 10 echo $time->getMinute(); // 15 echo $time->getSecond(); // 30 echo $time->getNano(); // 0 ``` -------------------------------- ### Get Current Date with System Clock Source: https://github.com/brick/date-time/blob/main/README.md Retrieves the current date using the default system clock. Ensure the TimeZone is specified. ```php use Brick\DateTime\LocalDate; use Brick\DateTime\TimeZone; echo LocalDate::now(TimeZone::utc()); // 2017-10-04 ``` -------------------------------- ### Get Duration Parts for Formatting Source: https://context7.com/brick/date-time/llms.txt Extract individual components of a duration (days, hours, minutes, seconds, milliseconds) for formatting purposes. Note that parts are within their respective unit ranges (e.g., hours 0-23). ```php use Brick\DateTime\Duration; // Get parts (for formatting) echo $duration->toDaysPart(); // days component echo $duration->toHoursPart(); // hours component (0-23) echo $duration->toMinutesPart(); // minutes component (0-59) echo $duration->toSecondsPart(); // seconds component (0-59) echo $duration->toMillisPart(); // milliseconds component (0-999) ``` -------------------------------- ### Get Current LocalTime Source: https://context7.com/brick/date-time/llms.txt Obtain the current time using LocalTime::now(), specifying the desired time zone, such as UTC. ```php use Brick\DateTime\LocalTime; use Brick\DateTime\TimeZone; // Get current time $now = LocalTime::now(TimeZone::utc()); ``` -------------------------------- ### Get Total Duration in Various Units Source: https://context7.com/brick/date-time/llms.txt Convert a Duration to its total value in days, hours, minutes, seconds, milliseconds, or nanoseconds. ```php use Brick\DateTime\Duration; // Get total in various units echo $duration->toDays(); // total days echo $duration->toHours(); // total hours echo $duration->toMinutes(); // total minutes echo $duration->toSeconds(); // total seconds echo $duration->toMillis(); // total milliseconds echo $duration->toNanos(); // total nanoseconds ``` -------------------------------- ### Get Current ZonedDateTime in a Specific Time Zone Source: https://context7.com/brick/date-time/llms.txt Use ZonedDateTime::now() with a TimeZone object to get the current date-time in that specific time zone. This accounts for the current offset and DST rules. ```php use Brick\DateTime\ZonedDateTime; use Brick\DateTime\TimeZone; $now = ZonedDateTime::now(TimeZone::parse('Asia/Tokyo')); ``` -------------------------------- ### Get Current LocalDateTime Source: https://context7.com/brick/date-time/llms.txt Obtain the current date and time using LocalDateTime::now(), specifying the desired time zone for accurate results. ```php use Brick\DateTime\LocalDateTime; use Brick\DateTime\TimeZone; // Get current date-time $now = LocalDateTime::now(TimeZone::parse('Europe/Paris')); ``` -------------------------------- ### Convert LocalTime to Seconds of Day Source: https://context7.com/brick/date-time/llms.txt Get the total number of seconds elapsed since midnight for a given LocalTime object. ```php use Brick\DateTime\LocalTime; // Get seconds since midnight $time = LocalTime::parse('10:15:30'); $seconds = $time->toSecondOfDay(); // 36930 ``` -------------------------------- ### Get LocalDateTime Components Source: https://context7.com/brick/date-time/llms.txt Extract individual date and time components, such as year, month, day, hour, minute, and second, from a LocalDateTime object. ```php use Brick\DateTime\LocalDateTime; // Get components $dateTime = LocalDateTime::of(2024, 6, 15, 14, 30, 45); $localDate = $dateTime->getDate(); $localTime = $dateTime->getTime(); echo $dateTime->getYear(); // 2024 echo $dateTime->getMonthValue(); // 6 echo $dateTime->getDayOfMonth(); // 15 echo $dateTime->getHour(); // 14 echo $dateTime->getMinute(); // 30 echo $dateTime->getSecond(); // 45 ``` -------------------------------- ### Get Components of ZonedDateTime Source: https://context7.com/brick/date-time/llms.txt Extract LocalDateTime, LocalDate, LocalTime, TimeZone, TimeZoneOffset, Instant, and epoch second from a ZonedDateTime object. These methods provide access to the underlying components. ```php use Brick\DateTime\ZonedDateTime; // Assuming $zonedDateTime is already created $localDateTime = $zonedDateTime->getDateTime(); $localDate = $zonedDateTime->getDate(); $localTime = $zonedDateTime->getTime(); $timeZone = $zonedDateTime->getTimeZone(); $offset = $zonedDateTime->getTimeZoneOffset(); $instant = $zonedDateTime->getInstant(); $epochSecond = $zonedDateTime->getEpochSecond(); ``` -------------------------------- ### DayOfWeek and Month Enums in PHP Source: https://context7.com/brick/date-time/llms.txt Use these enums for representing days of the week and months of the year in PHP 8.1+. They provide methods for creating instances from values, getting current values, navigating through days/months, and obtaining string representations. ```php use Brick\DateTime\DayOfWeek; use Brick\DateTime\Month; use Brick\DateTime\TimeZone; // DayOfWeek enum values $monday = DayOfWeek::MONDAY; // value: 1 $tuesday = DayOfWeek::TUESDAY; // value: 2 $wednesday = DayOfWeek::WEDNESDAY; // value: 3 $thursday = DayOfWeek::THURSDAY; // value: 4 $friday = DayOfWeek::FRIDAY; // value: 5 $saturday = DayOfWeek::SATURDAY; // value: 6 $sunday = DayOfWeek::SUNDAY; // value: 7 // Get current day of week $today = DayOfWeek::now(TimeZone::utc()); // Create from int value $day = DayOfWeek::from(1); // MONDAY // Get all days starting from a specific day $days = DayOfWeek::all(DayOfWeek::SUNDAY); // [SUNDAY, MONDAY, ...] // Check weekday/weekend echo $monday->isWeekday(); // true echo $saturday->isWeekend(); // true // Navigate days $nextDay = $monday->plus(1); // TUESDAY $prevDay = $monday->minus(1); // SUNDAY // Get string representation echo $monday->toString(); // "Monday" // Month enum values $january = Month::JANUARY; // value: 1 $february = Month::FEBRUARY; // value: 2 // ... through DECEMBER (value: 12) // Create from int value $month = Month::from(6); // JUNE // Get month lengths echo Month::FEBRUARY->getLength(false); // 28 (non-leap year) echo Month::FEBRUARY->getLength(true); // 29 (leap year) echo Month::JANUARY->getMinLength(); // 31 echo Month::FEBRUARY->getMaxLength(); // 29 // Get first day of year for this month echo Month::MARCH->getFirstDayOfYear(false); // 60 (non-leap) echo Month::MARCH->getFirstDayOfYear(true); // 61 (leap) // Navigate months $nextMonth = Month::JANUARY->plus(1); // FEBRUARY $prevMonth = Month::JANUARY->minus(1); // DECEMBER // Get string representation echo Month::JUNE->toString(); // "June" ``` -------------------------------- ### Get Duration Between Two ZonedDateTime Instances Source: https://context7.com/brick/date-time/llms.txt Calculate the Duration between two ZonedDateTime objects using getDurationTo(). The result is a Duration object representing the time difference. ```php use Brick\DateTime\ZonedDateTime; use Brick\DateTime\TimeZone; $zdt1 = ZonedDateTime::now(TimeZone::parse('America/New_York')); $zdt2 = ZonedDateTime::now(TimeZone::parse('Europe/Paris')); $duration = $zdt1->getDurationTo($zdt2); ``` -------------------------------- ### Create and Parse Periods using Brick’s DateTime Source: https://context7.com/brick/date-time/llms.txt Demonstrates creating Period objects using static methods like `of`, `ofYears`, `ofMonths`, `ofWeeks`, `ofDays`, and parsing ISO 8601 period strings. Includes creating a zero period. ```php use Brick\DateTime\Period; use Brick\DateTime\LocalDate; // Create periods $period = Period::of(1, 2, 3); // 1 year, 2 months, 3 days $period = Period::ofYears(2); // 2 years $period = Period::ofMonths(6); // 6 months $period = Period::ofWeeks(2); // 14 days $period = Period::ofDays(30); // 30 days // Parse from ISO 8601 period string $period = Period::parse('P1Y2M3D'); // 1 year, 2 months, 3 days $period = Period::parse('P2Y'); // 2 years $period = Period::parse('P6M'); // 6 months $period = Period::parse('P2W'); // 2 weeks (14 days) $period = Period::parse('-P1Y'); // negative 1 year // Zero period $zero = Period::zero(); // Calculate period between two dates $date1 = LocalDate::of(2020, 1, 15); $date2 = LocalDate::of(2024, 6, 20); $period = Period::between($date1, $date2); // or $period = $date1->until($date2); ``` -------------------------------- ### Create LocalTime from Components Source: https://context7.com/brick/date-time/llms.txt Instantiate LocalTime by providing hour, minute, second, and optionally nanosecond values. Calculations wrap around midnight. ```php use Brick\DateTime\LocalTime; // Create a time from components $time = LocalTime::of(14, 30, 45); // 14:30:45 $time = LocalTime::of(14, 30, 45, 123456789); // with nanoseconds ``` -------------------------------- ### Compare Instant Instances Source: https://context7.com/brick/date-time/llms.txt Compare two Instant objects using isBefore(), isAfter(), isEqualTo(), isFuture(), isPast(), and isBetweenInclusive(). These methods determine the chronological relationship between instants. ```php use Brick\DateTime\Instant; $instant1 = Instant::of(1000000000); $instant2 = Instant::of(2000000000); $epoch = Instant::epoch(); echo $instant1->isBefore($instant2); // true echo $instant1->isAfter($instant2); // false echo $instant1->isEqualTo($instant2); // false echo $instant1->isFuture(); // false (likely) echo $instant1->isPast(); // true (likely) echo $instant1->isBetweenInclusive($epoch, $instant2); // true ``` -------------------------------- ### Create Instant from Epoch Seconds and Nanoseconds Source: https://context7.com/brick/date-time/llms.txt Create an Instant object from epoch seconds and optionally nanoseconds. This represents a specific point in time, independent of time zones. ```php use Brick\DateTime\Instant; $instant = Instant::of(1718451600); // seconds since Unix epoch $instant = Instant::of(1718451600, 500000000); // with nanoseconds ``` -------------------------------- ### Create LocalDateTime from Components Source: https://context7.com/brick/date-time/llms.txt Instantiate LocalDateTime by providing year, month, day, hour, minute, second, and optionally nanosecond values. ```php use Brick\DateTime\LocalDateTime; // Create from components $dateTime = LocalDateTime::of(2024, 6, 15, 14, 30, 45); $dateTime = LocalDateTime::of(2024, 6, 15, 14, 30, 45, 123456789); // with nanos ``` -------------------------------- ### Compare and Convert Time Zones Source: https://context7.com/brick/date-time/llms.txt Demonstrates comparing time zones for equality using `isEqualTo` and converting Brick’s TimeZone objects to native PHP `DateTimeZone` objects and vice versa. ```php // Compare time zones $tz1 = TimeZone::parse('UTC'); $tz2 = TimeZone::utc(); echo $tz1->isEqualTo($tz2); // true // Convert to native DateTimeZone $nativeZone = $tz->toNativeDateTimeZone(); // Create from native DateTimeZone $tz = TimeZone::fromNativeDateTimeZone(new DateTimeZone('Europe/London')); ``` -------------------------------- ### Parse and Create Time Zones Source: https://context7.com/brick/date-time/llms.txt Demonstrates parsing various time zone formats (IANA regions, offsets, UTC) using `TimeZone::parse` and `TimeZone::utc`. Also shows creating offset-based and region-based time zones. ```php use Brick\DateTime\TimeZone; use Brick\DateTime\TimeZoneOffset; use Brick\DateTime\TimeZoneRegion; use Brick\DateTime\Instant; // Parse any time zone $tz = TimeZone::parse('America/New_York'); // TimeZoneRegion $tz = TimeZone::parse('+05:30'); // TimeZoneOffset $tz = TimeZone::parse('Z'); // UTC offset // Get UTC $utc = TimeZone::utc(); // Create offset-based time zones $offset = TimeZoneOffset::ofHours(5); // +05:00 $offset = TimeZoneOffset::ofHoursMinutes(5, 30); // +05:30 $offset = TimeZoneOffset::ofHoursMinutes(-8, 0); // -08:00 $offset = TimeZoneOffset::ofTotalSeconds(19800); // +05:30 $offset = TimeZoneOffset::parse('+05:30'); // Create region-based time zones $region = TimeZoneRegion::parse('Europe/Paris'); $region = TimeZoneRegion::parse('America/Los_Angeles'); $region = TimeZoneRegion::parse('Asia/Tokyo'); ``` -------------------------------- ### Compare ZonedDateTime Instances Source: https://context7.com/brick/date-time/llms.txt Compare two ZonedDateTime instances based on their Instant values using isBefore(), isAfter(), isFuture(), isPast(), and isEqualTo(). These methods determine the chronological order. ```php use Brick\DateTime\ZonedDateTime; use Brick\DateTime\TimeZone; $zdt1 = ZonedDateTime::now(TimeZone::parse('America/New_York')); $zdt2 = ZonedDateTime::now(TimeZone::parse('Europe/Paris')); echo $zdt1->isBefore($zdt2); echo $zdt1->isAfter($zdt2); echo $zdt1->isFuture(); echo $zdt1->isPast(); ``` -------------------------------- ### Normalize and Compare Periods Source: https://context7.com/brick/date-time/llms.txt Explains how to normalize a Period object to ensure months are less than 12 and demonstrates checking if a period is zero or equal to another period. ```php // Normalize (adjust months to < 12) $period = Period::of(0, 15, 0); // 15 months $normalized = $period->normalized(); echo $normalized->getYears(); // 1 echo $normalized->getMonths(); // 3 // Comparisons echo $period->isZero(); // false echo $period->isEqualTo($zero); // false ``` -------------------------------- ### Run Unit Tests with PHPUnit Source: https://github.com/brick/date-time/blob/main/README.md Executes the project's unit tests using the PHPUnit framework. ```sh vendor/bin/phpunit ``` -------------------------------- ### Run PHPStan Static Analysis Source: https://github.com/brick/date-time/blob/main/README.md Executes PHPStan to perform static analysis on the codebase, using a specified configuration file. ```sh tools/phpstan/vendor/bin/phpstan --configuration=tools/phpstan/phpstan.neon ``` -------------------------------- ### Modify Instant Components Source: https://context7.com/brick/date-time/llms.txt Create a new Instant with a modified epoch second or nanosecond component using withEpochSecond() and withNano(). ```php use Brick\DateTime\Instant; // Assuming $instant is already created $newInstant = $instant->withEpochSecond(1718500000); $newInstant = $instant->withNano(0); ``` -------------------------------- ### Convert Periods to Native DateInterval and ISO 8601 Source: https://context7.com/brick/date-time/llms.txt Shows how to convert a Brick’s Period object to a native PHP `DateInterval` object and how to represent a Period as an ISO 8601 string. ```php // Convert to native DateInterval $dateInterval = $period->toNativeDateInterval(); // Create from native DateInterval $period = Period::fromNativeDateInterval(new DateInterval('P1Y2M3D')); // ISO 8601 string representation echo $period->toISOString(); // "P4Y5M5D" ``` -------------------------------- ### Create ZonedDateTime from Instant and TimeZone Source: https://context7.com/brick/date-time/llms.txt Use ZonedDateTime::ofInstant() to create a ZonedDateTime from an Instant and a TimeZone. This method correctly applies the time zone's offset to the given point in time. ```php use Brick\DateTime\ZonedDateTime; use Brick\DateTime\Instant; use Brick\DateTime\TimeZone; $instant = Instant::of(1718451600); $zonedDateTime = ZonedDateTime::ofInstant($instant, TimeZone::parse('America/New_York')); ``` -------------------------------- ### Freeze Time with DefaultClock Source: https://context7.com/brick/date-time/llms.txt Freeze time to a specific instant for predictable testing. Ensure to reset the clock after tests. ```php use Brick\DateTime\DefaultClock; use Brick\DateTime\Instant; use Brick\DateTime\Duration; use Brick\DateTime\LocalDate; use Brick\DateTime\LocalDateTime; use Brick\DateTime\TimeZone; use Brick\DateTime\Clock\FixedClock; // Freeze time to a specific instant DefaultClock::freeze(Instant::of(1718451600)); // 2024-06-15T13:00:00Z echo Instant::now(); // Always returns the frozen time echo LocalDate::now(TimeZone::utc()); // 2024-06-15 ``` -------------------------------- ### Create Brick Date-Time from Native PHP DateTime Source: https://context7.com/brick/date-time/llms.txt Create Brick’s date-time objects from native PHP DateTime objects. This allows seamless integration when working with existing DateTime instances. ```php // Create from native DateTime $date = LocalDate::fromNativeDateTime(new DateTime('2024-06-15')); $time = LocalTime::fromNativeDateTime(new DateTime('14:30:45')); $dateTime = LocalDateTime::fromNativeDateTime(new DateTime('2024-06-15 14:30:45')); $zonedDateTime = ZonedDateTime::fromNativeDateTime( new DateTime('2024-06-15 14:30:45', new DateTimeZone('Europe/London')) ); ``` -------------------------------- ### Zero Duration Source: https://context7.com/brick/date-time/llms.txt Obtain a zero duration instance. ```php use Brick\DateTime\Duration; // Zero duration $zero = Duration::zero(); ``` -------------------------------- ### Check Coding Style with ECS Source: https://github.com/brick/date-time/blob/main/README.md Runs Easy Coding Standard to check for coding style violations, using a specified configuration file. ```sh tools/ecs/vendor/bin/ecs check --config tools/ecs/ecs.php ``` -------------------------------- ### Create LocalTime from Seconds of Day Source: https://context7.com/brick/date-time/llms.txt Construct a LocalTime object directly from the total number of seconds that have passed since midnight. ```php use Brick\DateTime\LocalTime; // Create from seconds of day $time = LocalTime::ofSecondOfDay(36930); // 10:15:30 ``` -------------------------------- ### Compare LocalTime Objects Source: https://context7.com/brick/date-time/llms.txt Determine the chronological order of two LocalTime objects using methods like isBefore() and isAfter(). ```php use Brick\DateTime\LocalTime; // Comparisons $time1 = LocalTime::of(9, 0); $time2 = LocalTime::of(17, 0); echo $time1->isBefore($time2); // true echo $time1->isAfter($time2); // false echo $time1->isBeforeOrEqualTo($time2); // true ``` -------------------------------- ### Scale Time Progression Source: https://github.com/brick/date-time/blob/main/README.md Sets the clock to a specific Instant and then scales time, making it move faster or slower. Reset the clock after testing. ```php use Brick\DateTime\DefaultClock; use Brick\DateTime\Instant; DefaultClock::travelTo(Instant::of(2000000000)); DefaultClock::scale(60); // 1 second becomes 60 seconds $a = Instant::now(); sleep(1); $b = Instant::now(); echo $a, PHP_EOL; // 2033-05-18T03:33:20.00188Z echo $b, PHP_EOL; // 2033-05-18T03:34:20.06632Z DefaultClock::reset(); ``` -------------------------------- ### Duration Comparisons Source: https://context7.com/brick/date-time/llms.txt Compare durations for equality, greater than, less than, and check if a duration is zero, positive, or negative. ```php use Brick\DateTime\Duration; // Comparisons $d1 = Duration::ofMinutes(60); $d2 = Duration::ofHours(1); echo $d1->isEqualTo($d2); // true echo $d1->isGreaterThan($d2); // false echo $d1->isLessThan($d2); // false echo $d1->isZero(); // false echo $d1->isPositive(); // true echo $d1->isNegative(); // false ``` -------------------------------- ### Perform Arithmetic on Instant Source: https://context7.com/brick/date-time/llms.txt Add or subtract seconds, minutes, hours, or days from an Instant object using plusSeconds(), minusSeconds(), etc. These operations return new Instant objects. ```php use Brick\DateTime\Instant; // Assuming $instant is already created $later = $instant->plusSeconds(60); $later = $instant->plusMinutes(5); $later = $instant->plusHours(1); $later = $instant->plusDays(1); $earlier = $instant->minusSeconds(60); $earlier = $instant->minusMinutes(5); $earlier = $instant->minusHours(1); $earlier = $instant->minusDays(1); ``` -------------------------------- ### Travel Through Time with DefaultClock Source: https://context7.com/brick/date-time/llms.txt Simulate the passage of time by traveling to a specific point or by a duration. Time continues to move forward from the travel point. ```php // Travel to a point in time (time continues to move forward) DefaultClock::reset(); // Reset first if previously frozen DefaultClock::travelTo(Instant::of(1000000000)); // 2001-09-09 $a = Instant::now(); sleep(1); $b = Instant::now(); echo $a->isBefore($b); // true - time moved forward ``` ```php // Travel by a duration (forward or backward) DefaultClock::reset(); DefaultClock::travelBy(Duration::ofDays(-365)); // Go back 1 year ``` -------------------------------- ### JSON Serialization of Brick Date-Time Objects Source: https://context7.com/brick/date-time/llms.txt Serialize various Brick’s date-time objects to JSON. All objects are represented as ISO 8601 strings in the JSON output. ```php use Brick\DateTime\LocalDate; use Brick\DateTime\LocalTime; use Brick\DateTime\LocalDateTime; use Brick\DateTime\ZonedDateTime; use Brick\DateTime\Instant; use Brick\DateTime\Duration; use Brick\DateTime\Period; use Brick\DateTime\TimeZone; // JSON serialization (all classes output ISO 8601 strings) $date = LocalDate::of(2024, 6, 15); $time = LocalTime::of(14, 30, 45); $dateTime = LocalDateTime::of(2024, 6, 15, 14, 30, 45); $instant = Instant::of(1718451600); $duration = Duration::ofHours(2); $period = Period::of(1, 2, 3); $data = [ 'date' => $date, 'time' => $time, 'dateTime' => $dateTime, 'instant' => $instant, 'duration' => $duration, 'period' => $period, ]; echo json_encode($data, JSON_PRETTY_PRINT); ``` -------------------------------- ### Find Minimum and Maximum LocalTime Source: https://context7.com/brick/date-time/llms.txt Determine the earliest and latest LocalTime from a set of provided LocalTime objects. ```php use Brick\DateTime\LocalTime; // Find min/max times $time1 = LocalTime::of(9, 0); $time2 = LocalTime::of(17, 0); $earliest = LocalTime::minOf($time1, $time2); $latest = LocalTime::maxOf($time1, $time2); ``` -------------------------------- ### Scale Time with DefaultClock Source: https://context7.com/brick/date-time/llms.txt Make time pass faster or slower by scaling its rate. This is useful for simulating long periods in short test durations. ```php // Scale time (make it move faster or slower) DefaultClock::reset(); DefaultClock::travelTo(Instant::of(2000000000)); DefaultClock::scale(60); // 1 real second = 60 simulated seconds $a = Instant::now(); sleep(1); $b = Instant::now(); // $b is approximately 60 seconds after $a in simulated time ``` ```php // Combine travel and scale DefaultClock::reset(); DefaultClock::travelTo(Instant::of(2000000000)); DefaultClock::scale(3600); // 1 real second = 1 simulated hour ``` -------------------------------- ### Find Minimum and Maximum LocalDateTime Source: https://context7.com/brick/date-time/llms.txt Determine the earliest and latest LocalDateTime from a set of provided LocalDateTime objects. ```php use Brick\DateTime\LocalDateTime; // Find min/max $dt1 = LocalDateTime::of(2024, 1, 1, 0, 0); $dt2 = LocalDateTime::of(2024, 12, 31, 23, 59); $earliest = LocalDateTime::minOf($dt1, $dt2); $latest = LocalDateTime::maxOf($dt1, $dt2); ``` -------------------------------- ### Period Arithmetic Operations Source: https://context7.com/brick/date-time/llms.txt Illustrates performing arithmetic operations on Period objects, including adding and subtracting years, months, and days, multiplying the period, and negating it. ```php // Arithmetic $longer = $period->plusYears(1); $longer = $period->plusMonths(6); $longer = $period->plusDays(10); $shorter = $period->minusYears(1); $shorter = $period->minusMonths(3); $shorter = $period->minusDays(5); $doubled = $period->multipliedBy(2); $negated = $period->negated(); ``` -------------------------------- ### Combine LocalDate and LocalTime Source: https://context7.com/brick/date-time/llms.txt Create a LocalDateTime object by combining a LocalDate and a LocalTime, or by specifying the date and time components directly. ```php use Brick\DateTime\LocalDateTime; use Brick\DateTime\LocalDate; use Brick\DateTime\LocalTime; // Combine date and time $date = LocalDate::of(2024, 6, 15); $time = LocalTime::of(14, 30); $dateTime = $date->atTime($time); // or $dateTime = $time->atDate($date); ``` -------------------------------- ### Convert Instant to ZonedDateTime Source: https://context7.com/brick/date-time/llms.txt Convert an Instant to a ZonedDateTime object by specifying a TimeZone. This associates the point in time with a specific time zone's rules and offset. ```php use Brick\DateTime\Instant; use Brick\DateTime\TimeZone; // Assuming $instant is already created $zonedDateTime = $instant->atTimeZone(TimeZone::parse('America/Los_Angeles')); ``` -------------------------------- ### Run Automated Refactoring with Rector Source: https://github.com/brick/date-time/blob/main/README.md Executes Rector to perform automated code refactoring, using a specified configuration file. ```sh tools/rector/vendor/bin/rector --config tools/rector/rector.php ``` -------------------------------- ### Set Custom Clock with DefaultClock Source: https://context7.com/brick/date-time/llms.txt Replace the default clock with a custom implementation, such as a FixedClock, for precise time control. ```php // Set a custom clock directly $fixedClock = new FixedClock(Instant::of(1718451600)); DefaultClock::set($fixedClock); ``` -------------------------------- ### Special LocalTime Values Source: https://context7.com/brick/date-time/llms.txt Access predefined LocalTime constants for midnight, noon, minimum, and maximum time values. ```php use Brick\DateTime\LocalTime; // Special times $midnight = LocalTime::midnight(); // 00:00 $noon = LocalTime::noon(); // 12:00 $min = LocalTime::min(); // 00:00:00.000000000 $max = LocalTime::max(); // 23:59:59.999999999 ``` -------------------------------- ### Special Instant Values Source: https://context7.com/brick/date-time/llms.txt Access special Instant values: Instant::epoch() for the Unix epoch, Instant::min() for the furthest past, and Instant::max() for the furthest future. ```php use Brick\DateTime\Instant; $epoch = Instant::epoch(); // 1970-01-01T00:00:00Z $min = Instant::min(); // far past $max = Instant::max(); // far future ``` -------------------------------- ### Travel to a Specific Point in Time Source: https://github.com/brick/date-time/blob/main/README.md Sets the clock to a specific Instant, allowing time to advance from that point. Reset the clock after use. ```php use Brick\DateTime\DefaultClock; use Brick\DateTime\Instant; DefaultClock::travelTo(Instant::of(2000000000)); $a = Instant::now(); sleep(1); $b = Instant::now(); echo $a, PHP_EOL; // 2033-05-18T03:33:20.000342Z echo $b, PHP_EOL; // 2033-05-18T03:33:21.000606Z DefaultClock::reset(); ``` -------------------------------- ### Calculate Duration Between Instants Source: https://context7.com/brick/date-time/llms.txt Calculate the duration between two Instant objects. The result is a Duration object representing the time difference. ```php use Brick\DateTime\Duration; use Brick\DateTime\Instant; // Calculate duration between two instants $start = Instant::of(1000000000); $end = Instant::of(1000003600); $duration = Duration::between($start, $end); // PT1H ``` -------------------------------- ### Fix Coding Style Issues with ECS Source: https://github.com/brick/date-time/blob/main/README.md Runs Easy Coding Standard to automatically fix coding style violations, using a specified configuration file. ```sh tools/ecs/vendor/bin/ecs check --config tools/ecs/ecs.php --fix ``` -------------------------------- ### Compare LocalDateTime Objects Source: https://context7.com/brick/date-time/llms.txt Determine the chronological order of two LocalDateTime objects using methods like isBefore() and isAfter(). Also check if a date-time is in the future or past relative to the current time. ```php use Brick\DateTime\LocalDateTime; use Brick\DateTime\TimeZone; // Comparisons $dt1 = LocalDateTime::of(2024, 1, 1, 0, 0); $dt2 = LocalDateTime::of(2024, 12, 31, 23, 59); echo $dt1->isBefore($dt2); // true echo $dt1->isAfter($dt2); // false echo $dt1->isFuture(TimeZone::utc()); // depends on current time echo $dt1->isPast(TimeZone::utc()); // depends on current time ``` -------------------------------- ### Parse LocalTime from ISO 8601 String Source: https://context7.com/brick/date-time/llms.txt Parse LocalTime objects from strings formatted according to ISO 8601 standards. Seconds are optional in the input string. ```php use Brick\DateTime\LocalTime; // Parse from ISO 8601 string $time = LocalTime::parse('10:15:30'); $time = LocalTime::parse('10:15'); // seconds optional ``` -------------------------------- ### ISO 8601 String Representation Source: https://context7.com/brick/date-time/llms.txt Convert a Duration object to its ISO 8601 string representation. ```php use Brick\DateTime\Duration; // ISO 8601 string representation echo $duration->toISOString(); // "PT1H" or "PT2H30M" etc. ``` -------------------------------- ### Change Time Zone of ZonedDateTime (Same Instant) Source: https://context7.com/brick/date-time/llms.txt Use withTimeZoneSameInstant() to change the time zone of a ZonedDateTime while preserving the exact moment in time (the Instant). The local date and time will change according to the new time zone's offset. ```php use Brick\DateTime\ZonedDateTime; use Brick\DateTime\TimeZone; // Assuming $zonedDateTime is already created $inTokyo = $zonedDateTime->withTimeZoneSameInstant(TimeZone::parse('Asia/Tokyo')); ``` -------------------------------- ### Modify LocalTime Components Source: https://context7.com/brick/date-time/llms.txt Create a new LocalTime object with specific components (hour, minute, second) modified, leaving other components unchanged. ```php use Brick\DateTime\LocalTime; // Modify specific components $time = LocalTime::parse('10:15:30'); $newTime = $time->withHour(8)->withMinute(0)->withSecond(0); ``` -------------------------------- ### YearMonth Class for Year-Month Combinations Source: https://context7.com/brick/date-time/llms.txt Use the YearMonth class to represent combinations of a year and month, suitable for credit card expirations or billing periods. It supports creation from values or ISO 8601 strings, component access, length information, arithmetic, modification, comparisons, and conversion to date ranges. ```php use Brick\DateTime\YearMonth; use Brick\DateTime\Month; use Brick\DateTime\TimeZone; use Brick\DateTime\LocalDate; // Create a year-month $ym = YearMonth::of(2024, 6); $ym = YearMonth::of(2024, Month::JUNE); // Parse from ISO 8601 string $ym = YearMonth::parse('2024-06'); // Get current year-month $current = YearMonth::now(TimeZone::utc()); // Get components echo $ym->getYear(); // 2024 echo $ym->getMonthValue(); // 6 echo $ym->getMonth(); // Month::JUNE // Get length information echo $ym->getLengthOfMonth(); // 30 echo $ym->getLengthOfYear(); // 366 (2024 is leap year) echo $ym->isLeapYear(); // true // Get specific days $firstDay = $ym->getFirstDay(); // LocalDate 2024-06-01 $lastDay = $ym->getLastDay(); // LocalDate 2024-06-30 $specificDay = $ym->atDay(15); // LocalDate 2024-06-15 // Arithmetic $nextMonth = $ym->plusMonths(1); $nextYear = $ym->plusYears(1); $prevMonth = $ym->minusMonths(1); $prevYear = $ym->minusYears(1); // Modify components $newYm = $ym->withYear(2025); $newYm = $ym->withMonth(12); $newYm = $ym->withMonth(Month::DECEMBER); // Comparisons $ym1 = YearMonth::of(2024, 1); $ym2 = YearMonth::of(2024, 12); echo $ym1->isBefore($ym2); // true echo $ym1->isAfter($ym2); // false echo $ym1->isEqualTo($ym2); // false // Convert to date range $range = $ym->toLocalDateRange(); // 2024-06-01 to 2024-06-30 // ISO 8601 string echo $ym->toISOString(); // "2024-06" ``` -------------------------------- ### Freeze Time to a Specific Point Source: https://github.com/brick/date-time/blob/main/README.md Freezes time to a specific Instant, making all subsequent calls to Instant::now() return the same value. Reset the clock afterwards. ```php use Brick\DateTime\DefaultClock; use Brick\DateTime\Instant; DefaultClock::freeze(Instant::of(2000000000)); $a = Instant::now(); sleep(1); $b = Instant::now(); echo $a, PHP_EOL; // 2033-05-18T03:33:20Z echo $b, PHP_EOL; // 2033-05-18T03:33:20Z DefaultClock::reset(); ``` -------------------------------- ### Create Durations Source: https://context7.com/brick/date-time/llms.txt Durations can be created from seconds, minutes, hours, days, milliseconds, or nanoseconds. You can also specify nanosecond adjustments when creating from seconds. ```php use Brick\DateTime\Duration; // Create durations $duration = Duration::ofSeconds(3600); // 1 hour $duration = Duration::ofSeconds(3600, 500000000); // 1h + 500ms in nanos $duration = Duration::ofMinutes(90); // 90 minutes $duration = Duration::ofHours(2); // 2 hours $duration = Duration::ofDays(1); // 24 hours $duration = Duration::ofMillis(1500); // 1.5 seconds $duration = Duration::ofNanos(1000000000); // 1 second ``` -------------------------------- ### Parse LocalDateTime from ISO 8601 String Source: https://context7.com/brick/date-time/llms.txt Parse LocalDateTime objects from strings formatted according to the ISO 8601 standard, which includes both date and time components. ```php use Brick\DateTime\LocalDateTime; // Parse from ISO 8601 string $dateTime = LocalDateTime::parse('2024-06-15T14:30:45'); ``` -------------------------------- ### Convert Brick Date-Time to Native PHP DateTime Source: https://context7.com/brick/date-time/llms.txt Convert Brick’s date-time objects to native PHP DateTime and DateTimeImmutable objects. This facilitates interoperability with other PHP libraries. ```php // Convert to native DateTime $nativeDate = $date->toNativeDateTime(); $nativeTime = $time->toNativeDateTime(); $nativeDateTime = $dateTime->toNativeDateTime(); $nativeZoned = ZonedDateTime::now(TimeZone::utc())->toNativeDateTime(); // Convert to DateTimeImmutable $immutableDate = $date->toNativeDateTimeImmutable(); $immutableDateTime = $dateTime->toNativeDateTimeImmutable(); ``` -------------------------------- ### Set and Reset Default Clock Source: https://github.com/brick/date-time/blob/main/README.md Changes the global default clock for all date-time operations and resets it. Remember to reset the clock after tests. ```php use Brick\DateTime\Clock\FixedClock; use Brick\DateTime\DefaultClock; use Brick\DateTime\Instant; use Brick\DateTime\LocalDate; use Brick\DateTime\TimeZone; DefaultClock::set(new FixedClock(Instant::of(1000000000))); echo LocalDate::now(TimeZone::utc()); // 2001-09-09 DefaultClock::reset(); // do not forget to reset the clock to the system clock! ``` -------------------------------- ### LocalTime Arithmetic Source: https://context7.com/brick/date-time/llms.txt Perform time arithmetic by adding or subtracting hours, minutes, seconds, or nanoseconds. Operations correctly wrap around midnight. ```php use Brick\DateTime\LocalTime; // Time arithmetic (wraps around midnight) $time = LocalTime::parse('10:15:30'); $later = $time->plusHours(5); $later = $time->plusMinutes(30); $later = $time->plusSeconds(90); $later = $time->plusNanos(1000000); $earlier = $time->minusHours(2); $earlier = $time->minusMinutes(15); ```