[ Web Proxy ]
URL:
Viewing: https://leafphp.dev/docs/utils/date [Back]  [Original]

Tick | Leaf PHP
Skip to content
Menu
Return to top
Sidebar Navigation SearchK
On this page
    CREATIVE LEAF

    We build products too.

    From the creators of Leaf PHP, a studio that's shipped frameworks and products used by millions. Let's build yours.

    Start your project
    Open with AI

    Tick

    Working with PHP dates can be challenging due to various date formats, handling different time zones, and tricky date calculations which are actually quite common. These issues can lead to inconsistencies if not managed carefully, and can be a source of bugs in your application.

    Tick is Leaf's small date module with a simple, clean API for working with dates in PHP. It is 100% compatible with PHP's native DateTime class, but offers a more fluent API inspired by Day.js.

    php
    tick()->now(); // get the current timestamp
    tick()->format('YYYY-MM-DD'); // format the current timestamp
    tick()
      ->startOf('month')
      ->add(1, 'day')
      ->set('year', 2018)
      ->format('YYYY-MM-DD HH:mm:ss');

    Setting up

    To get started with Tick, you need to install it using the Leaf CLI:

    Leaf CLIComposer
    bash
    leaf install date
    bash
    composer require leafs/date

    Once installed, you can start using Tick in your application.

    Parsing Dates

    You probably noticed the tick() function in the examples above. This function is the entry point for Tick and initializes a date for manipulation or formatting. You can pass a date string, a timestamp, or a DateTime object to the tick() function.

    php
    tick(); // will use today's date
    tick('2018-01-01 12:00:00'); // create a date from a string
    
    $date = new DateTime('2018-01-01 12:00:00');
    tick($date); // create a date from a DateTime object

    Tick is versatile and smart enough to handle dates correctly, so you can pass in any valid date string or timestamp and it will work as expected.

    You can also pass a timezone as the second argument. Just like day.js, this means the date string is a wall-clock time in that timezone: "noon in Tokyo", not "noon on my server converted to Tokyo":

    php
    // a user in Tokyo schedules a meeting for noon their time
    $meeting = tick('2026-01-15 12:00:00', 'Asia/Tokyo');
    
    $meeting->format('HH:mm');        // 12:00, noon on a Tokyo clock
    $meeting->utc()->format('HH:mm'); // 03:00, the same instant in UTC, ready to store

    Working with timezones New

    Timezones follow the day.js split: a timezone at construction parses in that zone (above), while tz() on an existing date converts the instant to another clock:

    php
    // stored in the database as UTC, rendered for a user in New York
    tick($row['starts_at'], 'UTC')
        ->tz('America/New_York')
        ->format('MMM D, hh:mm a');

    The full timezone API:

    php
    tick()->tz('Asia/Tokyo'); // convert to Tokyo time
    tick()->tz();             // get the current timezone name
    tick()->utc();            // convert to UTC
    tick()->utcOffset();      // offset from UTC in minutes (540 for Tokyo, -240 for New York in summer)

    Timezone names can be any supported timezone, an offset like +0200, or an abbreviation like BST. Invalid timezones throw an exception.

    The typical calendar-app flow is: parse the user's input in their timezone, store it in UTC, and convert to each viewer's timezone when rendering:

    php
    // saving: user says "12:00" and their profile says Asia/Tokyo
    $startsAt = tick(request()->get('starts_at'), $user->timezone)
        ->utc()
        ->format('YYYY-MM-DD HH:mm:ss');
    
    // rendering: another user in Accra views the event
    tick($event['starts_at'], 'UTC')->tz('Africa/Accra')->format('HH:mm');

    Upgrading from Leaf 4

    In earlier versions, tick($date, $timezone) converted the parsed date to the timezone instead of parsing in it. If you relied on that, move the timezone to a tz() call: tick($date)->tz($timezone).

    Getting and Setting Dates

    Tick provides methods for getting and setting various parts of a date, such as the year, month, day, hour, minute, second, and millisecond. This uses a syntax where the same function can be used to get or set a value.

    php
    tick()->second(30); // set the second to 30
    tick()->second(); // get the second

    This works for all parts of a date, including the year, month, day, hour, minute, second, and millisecond.

    php
    tick()->year(2018); // set the year to 2018
    tick()->year(); // get the year
    
    tick()->month(); // gets current month
    tick()->month(0); // returns new tick object
    
    tick()->day(); // gets day of current month
    tick()->day(1); // returns new tick object
    
    tick()->hour(); // gets current hour
    $newDate = tick()->hour(12); // returns new tick object
    
    tick()->minute(); // gets current minute
    tick()->minute(59); // returns new tick object
    
    tick()->second(); // gets current second
    tick()->second(1); // returns new tick object
    
    tick()->millisecond(); // gets current millisecond
    tick()->millisecond(1); // returns new tick object

    You can also use the get() and set() methods to get and set values.

    php
    tick()->get('year'); // get the year
    tick()->set('year', 2018); // set the year to 2018

    List of all available units

    UnitShorthandDescription
    dateDDate of Month
    daydDay of Week (Sunday as 0, Saturday as 6)
    monthMMonth (January as 0, December as 11)
    yearyYear
    hourhHour
    minutemMinute
    secondsSecond
    millisecondmsMillisecond

    Manipulating Dates

    This is a fancy way of saying "changing dates" into some other kind of date. Tick provides straightforward methods for adding, subtracting, setting, and manipulating dates in various ways.

    All manipulation methods return a new Tick object, so you can chain them together.

    php
    tick()->add(1, 'day')->format('YYYY-MM-DD');

    Adding and Subtracting Dates

    Tick allows you to add time to a date using the add() method. You can add any number of years, months, days, hours, minutes, seconds, or milliseconds to a date.

    php
    tick()->add(1, 'day');
    tick()->add(1, 'week');

    You can also subtract time from a date using the subtract() method.

    php
    tick()->subtract(1, 'day');
    tick()->subtract(1, 'week');

    This is a list of all available units that can be used with the add() and subtract() methods:

    UnitShorthandDescription
    daydDay
    weekwWeek
    monthMMonth
    yearyYear
    hourhHour
    minutemMinute
    secondsSecond
    millisecondmsMillisecond

    Getting the start/end of a unit

    You can get the start of a unit using the startOf() method. This method sets the date to the start of the specified unit, such as the start of the day, month, or year. For example, to get the first day of the month or the first day of the year, you can use the following code:

    php
    tick()->startOf('month'); // => 2024-10-01 00:00:00
    tick()->startOf('year'); // => 2024-01-01 00:00:00

    You can also use the endOf() method to get the end of a unit. This method sets the date to the end of the specified unit, such as the end of the day, month, or year. For example, to get the last day of the month or the last day of the year, you can use the following code:

    php
    tick()->endOf('month'); // => 2024-10-31 23:59:59
    tick()->endOf('year'); // => 2024-12-31 23:59:59

    These methods are useful for getting the start or end of a unit when you need to perform calculations or comparisons based on the start or end of a unit.

    The following units are available for use with the startOf() and endOf() methods:

    UnitShorthandDescription
    yearyJanuary 1st, 00:00 this year
    monthMthe first day of this month, 00:00
    weekwthe first day of this week, 00:00 (locale aware)
    dateD00:00 today
    dayd00:00 today
    hourhnow, but with 0 mins, 0 secs, and 0 ms
    minutemnow, but with 0 seconds and 0 milliseconds
    secondsnow, but with 0 milliseconds

    Formatting Dates

    Formatting dates is a common task when working with dates in PHP. Formatting a date allows you to display the date in a specific format, such as YYYY-MM-DD or DD/MM/YYYY. Tick provides a format() method that allows you to format a date using a format string.

    php
    tick()->format();
    // '2024-10-03T18:04:37+00:00'
    // current date in ISO8601, without fraction seconds
    
    tick('2019-01-25')->format('DD/MM/YYYY'); // '25/01/2019'

    You can combine various format tokens to create a custom date format. The following format tokens are available for use with the format() method:

    FormatOutputDescription
    YY70Two-digit year
    YYYY1970Four-digit year
    M1-12The month, beginning at 1
    MM01-12The month, 2-digits
    MMMJan-DecThe abbreviated month name
    MMMMJanuary-DecemberThe full month name
    D1-31The day of the month
    DD01-31The day of the month, 2-digits
    d0-6The day of the week, with Sunday as 0
    ddSu-SaThe min name of the day of the week
    dddSun-SatThe short name of the day of the week
    ddddSunday-SaturdayThe name of the day of the week
    H0-23The hour
    HH00-23The hour, 2-digits
    h1-12The hour, 12-hour clock
    hh01-12The hour, 12-hour clock, 2-digits
    m0-59The minute
    mm00-59The minute, 2-digits
    s0-59The second
    ss00-59The second, 2-digits
    SSS000-999The millisecond, 3-digits
    Z+01:00Offset from UTC, e.g. +01:00
    ZZ+0100Offset from UTC, e.g. +0100
    AAMAM, PM
    aamam, pm

    Anything you pass into the format() method will be formatted according to the format string you provide. If you want to ignore parts of information you pass into the format() method, you can wrap them in square brackets.

    php
    tick('2019-01-25')->format('[YYYYescape] YYYY-MM-DDTHH:mm:ssZ[Z]');
    // 'YYYYescape 2019-01-25T00:00:000Z'

    YYYYescape got ignored instead of turning into a year, which is handy when you want to include some text in your date format.

    Time from now

    You can get how far a date is from now using the fromNow() method. This method returns a string that represents the difference between the date and the current date in a human-readable format.

    php
    tick('2014-10-01')->fromNow(); // 10 years ago
    tick('2027-10-04')->fromNow(); // in 3 years

    If you want to remove the suffix (ago or in), you can pass true as the first argument to the fromNow() method.

    php
    tick('2014-10-01')->fromNow(true); // 10 years
    tick('2027-10-04')->fromNow(true); // 3 years

    Time from a date

    If you want to check how much time has passed since a specific date, you can use the from() method. This method returns a string that represents the difference between the date and the specified date in a human-readable format.

    php
    tick('2014-10-01')->from('2015-10-01'); // 1 year ago
    tick('2015-10-01')->from('2014-10-01'); // in 1 year

    If you want to remove the suffix (ago or in), you can pass true as the first argument to the from() method.

    php
    tick('2014-10-01')->from('2015-10-01', true); // 1 year
    tick('2015-10-01')->from('2014-10-01', true); // 1 year

    Difference between dates New

    Human-readable strings are great for display, but sometimes you need an actual number, like the number of nights between a check-in and a check-out. As of leafs/date 5.1, you can use the diff() method to get the difference between two dates as a signed whole number:

    php
    tick($checkOut)->diff($checkIn, 'days'); // eg. 3
    tick('2025-01-01')->diff('2025-03-01', 'months'); // -2

    diff() follows the same semantics as day.js: it takes the date to compare against as its first argument and the unit as its second, and returns a positive number when the tick instance is after the compared date, and a negative one when it's before. The available units are years, months, days, hours, minutes, and seconds, and the compared date can be a string, a DateTime object, or another tick() instance.

    Day differences are calendar-aware, so a stay that crosses a daylight saving boundary still counts the number of calendar days you'd expect instead of drifting by an hour's worth of math.

    Querying Dates

    Querying dates allows you to check relationships between dates, such as whether a date is before or after another date. Tick provides methods for querying dates, such as isBefore(), isAfter(), and isSame().

    Is Before

    This indicates whether the Tick object is before the other supplied date-time.

    php
    tick()->isBefore('2011-01-01');

    Is Same

    This indicates whether the Tick object is the same as the other supplied date-time.

    php
    tick()->isSame(new \DateTime('2011-01-01'));

    Is After

    This indicates whether the Tick object is after the other supplied date-time.

    php
    tick()->isAfter('2011-01-01');

    Is Between

    This indicates whether the Tick object is between two other supplied date-time.

    php
    tick('2010-10-20')
      ->isBetween('2010-10-19', new \DateTime('2010-10-25'));

    Is Between Or Equal

    This indicates whether the Tick object is between two other supplied date-time or equal to one of them.

    php
    tick('2010-10-20')
      ->isBetweenOrEqual('2010-10-19', new \DateTime('2010-10-25'));

    Is same day

    This indicates whether the Tick object is the same day as the other supplied date-time.

    php
    tick('2010-10-20')->isSameDay('2010-10-20');

    Is same month

    This indicates whether the Tick object is the same month as the other supplied date-time.

    php
    
    
    tick('2010-10-20')->isSameMonth('2010-10-20');

    Is same year

    This indicates whether the Tick object is the same year as the other supplied date-time.

    php
    tick('2010-10-20')->isSameYear('2010-10-20');

    Is Leap Year

    This indicates whether the Tick object's year is a leap year or not.

    php
    tick('2000-01-01')->isLeapYear(); // true

    Is DateTime

    This indicates whether the Tick object is a DateTime object or not.

    php
    tick()->isDateTime('2000-01-01'); // false
    Pager

    Web Proxy Viewer  |  New URL  |  Original Page