Dates and Times

CodeIgniter provides a fully-localized, immutable, date/time class that is built on PHP’s DateTime object, but uses the Intlextension’s features to convert times across timezones and display the output correctly for different locales. This classis the Time class and lives in the CodeIgniter\I18n namespace.

Note

Since the Time class extends DateTime, if there are features that you need that this class doesn’t provide,you can likely find them within the DateTime class itself.

Instantiating

There are several ways that a new Time instance can be created. The first is simply to create a new instancelike any other class. When you do it this way, you can pass in a string representing the desired time. This canbe any string that PHP’s strtotime function can parse:

  1. use CodeIgniter\I18n\Time;
  2.  
  3. $myTime = new Time('+3 week');
  4. $myTime = new Time('now');

You can pass in strings representing the timezone and the locale in the second and parameters, respectively. Timezonescan be any supported by PHP’s DateTimeZone class. The locale can beany supported by PHP’s Locale class. If no locale or timezone isprovided, the application defaults will be used.

  1. $myTime = new Time('now', 'America/Chicago', 'en_US');

now()

The Time class has several helper methods to instantiate the class. The first of these is the now() methodthat returns a new instance set to the current time. You can pass in strings representing the timezone and the localein the second and parameters, respectively. If no locale or timezone is provided, the application defaults will be used.

  1. $myTime = Time::now('America/Chicago', 'en_US');

parse()

This helper method is a static version of the default constructor. It takes a string acceptable as DateTime’sconstructor as the first parameter, a timezone as the second parameter, and the locale as the third parameter.:

  1. $myTime = Time::parse('next Tuesday', 'America/Chicago', 'en_US');

today()

Returns a new instance with the date set to the current date, and the time set to midnight. It accepts stringsfor the timezone and locale in the second and third parameters:

  1. $myTime = Time::today('America/Chicago', 'en_US');

yesterday()

Returns a new instance with the date set to the yesterday’s date and the time set to midnight. It accepts stringsfor the timezone and locale in the second and third parameters:

  1. $myTime = Time::yesterday('America/Chicago', 'en_US');

tomorrow()

Returns a new instance with the date set to tomorrow’s date and the time set to midnight. It accepts stringsfor the timezone and locale in the second and third parameters:

  1. $myTime = Time::tomorrow('America/Chicago', 'en_US');

createFromDate()

Given separate inputs for year, month, and day, will return a new instance. If any of these parametersare not provided, it will use the current value to fill it in. Accepts strings for the timezone and locale in thefourth and fifth parameters:

  1. $today = Time::createFromDate(); // Uses current year, month, and day
  2. $anniversary = Time::createFromDate(2018); // Uses current month and day
  3. $date = Time::createFromDate(2018, 3, 15, 'America/Chicago', 'en_US');

createFromTime()

Like createFromDate except it is only concerned with the hours, minutes, and seconds. Uses thecurrent day for the date portion of the Time instance. Accepts strings for the timezone and locale in thefourth and fifth parameters:

  1. $lunch = Time::createFromTime(11, 30) // 11:30 am today
  2. $dinner = Time::createFromTime(18, 00, 00) // 6:00 pm today
  3. $time = Time::createFromTime($hour, $minutes, $seconds, $timezone, $locale);

create()

A combination of the previous two methods, takes year, month, day, hour, minutes, and secondsas separate parameters. Any value not provided will use the current date and time to determine. Accepts strings for thetimezone and locale in the fourth and fifth parameters:

  1. $time = Time::create($year, $month, $day, $hour, $minutes, $seconds, $timezone, $locale);

createFromFormat()

This is a replacement for DateTime’s method of the same name. This allows the timezone to be set at the same time,and returns a Time instance, instead of DateTime:

  1. $time = Time::createFromFormat('j-M-Y', '15-Feb-2009', 'America/Chicago');

createFromTimestamp()

This method takes a UNIX timestamp and, optionally, the timezone and locale, to create a new Time instance:

  1. $time = Time::createFromTimestamp(1501821586, 'America/Chicago', 'en_US');

instance()

When working with other libraries that provide a DateTime instance, you can use this method to convert thatto a Time instance, optionally setting the locale. The timezone will be automatically determined from the DateTimeinstance passed in:

  1. $dt = new DateTime('now');
  2. $time = Time::instance($dt, 'en_US');

toDateTime()

While not an instantiator, this method is the opposite of the instance method, allowing you to convert a Timeinstance into a DateTime instance. This preserves the timezone setting, but loses the locale, since DateTime isnot aware of locales:

  1. $datetime = Time::toDateTime();

Displaying the Value

Since the Time class extends DateTime, you get all of the output methods that provides, including the format() method.However, the DateTime methods do not provide a localized result. The Time class does provide a number of helper methodsto display localized versions of the value, though.

toLocalizedString()

This is the localized version of DateTime’s format() method. Instead of using the values you might be familiar with, though,you must use values acceptable to the IntlDateFormatter class.A full listing of values can be found here.

  1. $time = Time::parse('March 9, 2016 12:00:00', 'America/Chicago');
  2. echo $time->toLocalizedString('MMM d, yyyy'); // March 9, 2016

toDateTimeString()

This is the first of three helper methods to work with the IntlDateFormatter without having to remember their values.This will return a string formatted as you would commonly use for datetime columns in a database (Y-m-d H:i:s):

  1. $time = Time::parse('March 9, 2016 12:00:00', 'America/Chicago');
  2. echo $time->toDateTimeString(); // 2016-03-09 12:00:00

toDateString()

Displays just the date portion of the Time:

  1. $time = Time::parse('March 9, 2016 12:00:00', 'America/Chicago');
  2. echo $time->toDateString(); // 2016-03-09

toTimeString()

Displays just the time portion of the value:

  1. $time = Time::parse('March 9, 2016 12:00:00', 'America/Chicago');
  2. echo $time->toTimeString(); // 12:00:00

humanize()

This methods returns a string that displays the difference between the current date/time and the instance in ahuman readable format that is geared towards being easily understood. It can create strings like ‘3 hours ago’,‘in 1 month’, etc:

  1. // Assume current time is: March 10, 2017 (America/Chicago)
  2. $time = Time::parse('March 9, 2016 12:00:00', 'America/Chicago');
  3.  
  4. echo $time->humanize(); // 1 year ago

The exact time displayed is determined in the following manner:

Time differenceResult
$time > 1 year && < 2 yearsin 1 year / 1 year ago
$time > 1 month && < 1 yearin 6 months / 6 months ago
$time > 7 days && < 1 monthin 3 weeks / 3 weeks ago
$time > today && < 7 daysin 4 days / 4 days ago
$time == tomorrow / yesterdayTomorrow / Yesterday
$time > 59 minutes && < 1 day1:37pm
$time > now && < 1 hourin 35 minutes / 35 minutes ago
$time == nowNow

The exact language used is controlled through the language file, Time.php.

Working with Individual Values

The Time object provides a number of methods to allow to get and set individual items, like the year, month, hour, etc,of an existing instance. All of the values retrieved through the following methods will be fully localized and respectthe locale that the Time instance was created with.

All of the following getX and setX methods can also be used as if they were a class property. So, any calls to methodslike getYear can also be accessed through $time->year, and so on.

Getters

The following basic getters exist:

  1. $time = Time::parse('August 12, 2016 4:15:23pm');
  2.  
  3. echo $time->getYear(); // 2016
  4. echo $time->getMonth(); // 8
  5. echo $time->getDay(); // 12
  6. echo $time->getHour(); // 16
  7. echo $time->getMinute(); // 15
  8. echo $time->getSecond(); // 23
  9.  
  10. echo $time->year; // 2016
  11. echo $time->month; // 8
  12. echo $time->day; // 12
  13. echo $time->hour; // 16
  14. echo $time->minute; // 15
  15. echo $time->second; // 23

In addition to these, a number of methods exist to provide additional information about the date:

  1. $time = Time::parse('August 12, 2016 4:15:23pm');
  2.  
  3. echo $time->getDayOfWeek(); // 6 - but may vary based on locale's starting day of the week
  4. echo $time->getDayOfYear(); // 225
  5. echo $time->getWeekOfMonth(); // 2
  6. echo $time->getWeekOfYear(); // 33
  7. echo $time->getTimestamp(); // 1471018523 - UNIX timestamp
  8. echo $time->getQuarter(); // 3
  9.  
  10. echo $time->dayOfWeek; // 6
  11. echo $time->dayOfYear; // 225
  12. echo $time->weekOfMonth; // 2
  13. echo $time->weekOfYear; // 33
  14. echo $time->timestamp; // 1471018523
  15. echo $time->quarter; // 3

getAge()

Returns the age, in years, of between the Time’s instance and the current time. Perfect for checkingthe age of someone based on their birthday:

  1. $time = Time::parse('5 years ago');
  2.  
  3. echo $time->getAge(); // 5
  4. echo $time->age; // 5

getDST()

Returns boolean true/false based on whether the Time instance is currently observing Daylight Savings Time:

  1. echo Time::createFromDate(2012, 1, 1)->getDst(); // false
  2. echo Time::createFromDate(2012, 9, 1)->dst; // true

getLocal()

Returns boolean true if the Time instance is in the same timezone as the application is currently running in:

  1. echo Time::now()->getLocal(); // true
  2. echo Time::now('Europe/London'); // false

getUtc()

Returns boolean true if the Time instance is in UTC time:

  1. echo Time::now('America/Chicago')->getUtc(); // false
  2. echo Time::now('UTC')->utc; // true

getTimezone()

Returns a new DateTimeZone object set the timezone of the Timeinstance:

  1. $tz = Time::now()->getTimezone();
  2. $tz = Time::now()->timezone;
  3.  
  4. echo $tz->getName();
  5. echo $tz->getOffset();

getTimezoneName()

Returns the full timezone string of the Time instance:

  1. echo Time::now('America/Chicago')->getTimezoneName(); // America/Chicago
  2. echo Time::now('Europe/London')->timezoneName; // Europe/London

Setters

The following basic setters exist. If any of the values set are out of range, an InvalidArgumentExeption will bethrown.

Note

All setters will return a new Time instance, leaving the original instance untouched.

Note

All setters will throw an InvalidArgumentException if the value is out of range.

  1. $time = $time->setYear(2017);
  2. $time = $time->setMonthNumber(4); // April
  3. $time = $time->setMonthLongName('April');
  4. $time = $time->setMonthShortName('Feb'); // February
  5. $time = $time->setDay(25);
  6. $time = $time->setHour(14); // 2:00 pm
  7. $time = $time->setMinute(30);
  8. $time = $time->setSecond(54);

setTimezone()

Converts the time from it’s current timezone into the new one:

  1. $time = Time::parse('May 10, 2017', 'America/Chicago');
  2. $time2 = $time->setTimezone('Europe/London'); // Returns new instance converted to new timezone
  3.  
  4. echo $time->timezoneName; // American/Chicago
  5. echo $time2->timezoneName; // Europe/London

setTimestamp()

Returns a new instance with the date set to the new timestamp:

  1. $time = Time::parse('May 10, 2017', 'America/Chicago');
  2. $time2 = $time->setTimestamp(strtotime('April 1, 2017'));
  3.  
  4. echo $time->toDateTimeString(); // 2017-05-10 00:00:00
  5. echo $time2->toDateTimeString(); // 2017-04-01 00:00:00

Modifying the Value

The following methods allow you to modify the date by adding or subtracting values to the current Time. This will notmodify the existing Time instance, but will return a new instance.

  1. $time = $time->addSeconds(23);
  2. $time = $time->addMinutes(15);
  3. $time = $time->addHours(12);
  4. $time = $time->addDays(21);
  5. $time = $time->addMonths(14);
  6. $time = $time->addYears(5);
  7.  
  8. $time = $time->subSeconds(23);
  9. $time = $time->subMinutes(15);
  10. $time = $time->subHours(12);
  11. $time = $time->subDays(21);
  12. $time = $time->subMonths(14);
  13. $time = $time->subYears(5);

Comparing Two Times

The following methods allow you to compare one Time instance with another. All comparisons are first converted to UTCbefore comparisons are done, to ensure that different timezones respond correctly.

equals()

Determines if the datetime passed in is equal to the current instance. Equal in this case means that they represent thesame moment in time, and are not required to be in the same timezone, as both times are converted to UTC and comparedthat way:

  1. $time1 = Time::parse('January 10, 2017 21:50:00', 'America/Chicago');
  2. $time2 = Time::parse('January 11, 2017 03:50:00', 'Europe/London');
  3.  
  4. $time1->equals($time2); // true

The value being tested against can be a Time instance, a DateTime instance, or a string with the full date time ina manner that a new DateTime instance can understand. When passing a string as the first parameter, you can passa timezone string in as the second parameter. If no timezone is given, the system default will be used:

  1. $time1->equals('January 11, 2017 03:50:00', 'Europe/London'); // true

sameAs()

This is identical to the equals method, except that it only returns true when the date, time, AND timezone areall identical:

  1. $time1 = Time::parse('January 10, 2017 21:50:00', 'America/Chicago');
  2. $time2 = Time::parse('January 11, 2017 03:50:00', 'Europe/London');
  3.  
  4. $time1->sameAs($time2); // false
  5. $time2->sameAs('January 10, 2017 21:50:00', 'America/Chicago'); // true

isBefore()

Checks if the passed in time is before the the current instance. The comparison is done against the UTC versions ofboth times:

  1. $time1 = Time::parse('January 10, 2017 21:50:00', 'America/Chicago');
  2. $time2 = Time::parse('January 11, 2017 03:50:00', 'America/Chicago');
  3.  
  4. $time1->isBefore($time2); // true
  5. $time2->isBefore($time1); // false

The value being tested against can be a Time instance, a DateTime instance, or a string with the full date time ina manner that a new DateTime instance can understand. When passing a string as the first parameter, you can passa timezone string in as the second parameter. If no timezone is given, the system default will be used:

  1. $time1->isBefore('March 15, 2013', 'America/Chicago'); // false

isAfter()

Works exactly the same as isBefore() except checks if the time is after the time passed in:

  1. $time1 = Time::parse('January 10, 2017 21:50:00', 'America/Chicago');
  2. $time2 = Time::parse('January 11, 2017 03:50:00', 'America/Chicago');
  3.  
  4. $time1->isAfter($time2); // false
  5. $time2->isAfter($time1); // true

Viewing Differences

To compare two Times directly, you would use the difference() method, which returns a CodeIgniterI18nTimeDifferenceinstance. The first parameter is either a Time instance, a DateTime instance, or a string with the date/time. Ifa string is passed in the first parameter, the second parameter can be a timezone string:

  1. $time = Time::parse('March 10, 2017', 'America/Chicago');
  2.  
  3. $diff = $time->difference(Time::now());
  4. $diff = $time->difference(new DateTime('July 4, 1975', 'America/Chicago');
  5. $diff = $time->difference('July 4, 1975 13:32:05', 'America/Chicago');

Once you have the TimeDifference instance, you have several methods you can use to find information about the differencebetween the two times. The value returned will be negative if it was in the past, or positive if in the future fromthe original time:

  1. $current = Time::parse('March 10, 2017', 'America/Chicago');
  2. $test = Time::parse('March 10, 2010', 'America/Chicago');
  3.  
  4. $diff = $current->difference($test);
  5.  
  6. echo $diff->getYears(); // -7
  7. echo $diff->getMonths(); // -84
  8. echo $diff->getWeeks(); // -365
  9. echo $diff->getDays(); // -2557
  10. echo $diff->getHours(); // -61368
  11. echo $diff->getMinutes(); // -3682080
  12. echo $diff->getSeconds(); // -220924800

You can use either getX() methods, or access the calculate values as if they were properties:

  1. echo $diff->years; // -7
  2. echo $diff->months; // -84
  3. echo $diff->weeks; // -365
  4. echo $diff->days; // -2557
  5. echo $diff->hours; // -61368
  6. echo $diff->minutes; // -3682080
  7. echo $diff->seconds; // -220924800

humanize()

Much like Time’s humanize() method, this returns a string that displays the difference between the times in ahuman readable format that is geared towards being easily understood. It can create strings like ‘3 hours ago’,‘in 1 month’, etc. The biggest differences are in how very recent dates are handled:

  1. $current = Time::parse('March 10, 2017', 'America/Chicago')
  2. $test = Time::parse('March 9, 2016 12:00:00', 'America/Chicago');
  3.  
  4. $diff = $current->difference($test)
  5.  
  6. echo $diff->humanize(); // 1 year ago

The exact time displayed is determined in the following manner:

Time differenceResult
$time > 1 year && < 2 yearsin 1 year / 1 year ago
$time > 1 month && < 1 yearin 6 months / 6 months ago
$time > 7 days && < 1 monthin 3 weeks / 3 weeks ago
$time > today && < 7 daysin 4 days / 4 days ago
$time > 1 hour && < 1 dayin 8 hours / 8 hours ago
$time > 1 minute && < 1 hourin 35 minutes / 35 minutes ago
$time < 1 minuteNow

The exact language used is controlled through the language file, Time.php.