calculate intervals & perform date arithmetic in PHP
Here’s another one of those things that people find scary: date and time. Why don’t we demystify this topic as well. Let’s look at the traditional way of doing this first and then the Carbon way in the next couple of articles. We’ll also look at time addition and subtraction in the next article with the
The easiest way to get into this is with examples. We’ll be tackling the following date and time functions:
The getdate() function returns an array with the following values for the local time.
/app/94 DateTime/index.php:3: array (size=11) 'seconds' => int 18 'minutes' => int 21 'hours' => int 21 'mday' => int 19 'wday' => int 6 'mon' => int 11 'year' => int 2022 'yday' => int 322 'weekday' => string 'Saturday' (length=8) 'month' => string 'November' (length=8) 0 => int 1668892878
The array keys represent:
hours represent the numeric representation of seconds, minutes, and hours respectively
mday states the numeric day of the month (from 1 to 31)
wday states the numeric representation of the day of the week with
0 being Sunday and
6 being Saturday
mon is the numeric representation of the month
year is the 4 digit year
yday is the numeric representation of the current day, from
weekday is the textual representation of the day of the week, i.e.
month is the textual representation of the month, i.e.
0 is the seconds since Unix Epoch
You can store the
getdate() result in a variable and then call on the values that you need.
$current_date_time = getdate(); echo $current_date_time['weekday'];
localtime() returns an array identical to that of the structure returned by the C function call.
- “tm_sec” — represents the seconds, from
- “tm_min” — represents the minutes, from
- “tm_hour” — represents the hours, from
- “tm_mday” — represents the day of the month, from
- “tm_mon” — represents the month of the year, from
- “tm_year” — represents the years since 1900
- “tm_wday” — represents the day of the week,
- “tm_yday” — represents the day of the year, from
- “tm_isdst” — Positive if daylight savings time is in effect,
0if not, negative if unknown.
Unfortunately the keys are not displayed. So you’ll need to know what the index value represents.
Saturday /app/94 DateTime/index.php:6: array (size=9) 0 => int 25 //tm_sec 1 => int 31 //tm_min 2 => int 21 //tm_hour 3 => int 19 //tm_mday 4 => int 10 //tm_mon 5 => int 122 //tm_year 6 => int 6 //tm_wday 7 => int 322 //tm_yday 8 => int 0 //tm_isdst
To get the current year, you’ll need to add
1900 to the year.
$localtime = localtime(); $current_year = $localtime + 1900; echo $current_year;
This is the most used function. This is where you’ll get most of your data from, most of the time. The
date() function expects a formatter string as an argument Which values are accepted?
Accepted values for
date() argument string.
d represents the 2 digit day of the month, from 01 to 31 (including the leading zero)
D represents the day in three letter text format from
j represents the 2 digit day of the month, from 1 to 31 (without the leading zero)
l (lowercase ‘L’) A full textual representation of the day of the week
N ISO 8601 numeric representation of the day of the week
1 (for Monday) through
7 (for Sunday)
S English ordinal suffix for the day of the month, 2 characters
th. Works well with
w Numeric representation of the day of the week
0 (for Sunday) through
6 (for Saturday)
z The day of the year (starting from 0)
W ISO 8601 week number of year, weeks starting on MondayExample:
42 (the 42nd week in the year)
F A full textual representation of a month, such as January or March
m Numeric representation of a month, with leading zeros
M A short textual representation of a month, three letters
n Numeric representation of a month, without leading zeros
t Number of days in the given month
L Whether it’s a leap year
1 if it is a leap year,
o ISO 8601 week-numbering year. This has the same value as
Y, except that if the ISO week number (
W) belongs to the previous or next year, that year is used instead.Examples:
X An expanded full numeric representation of a year, at least 4 digits, with
- for years BCE, and
+ for years CE.Examples:
x An expanded full numeric representation if required, or a standard full numeral representation if possible (like
Y). At least four digits. Years BCE are prefixed with a
-. Years beyond (and including)
10000 are prefixed by a
Y A full numeric representation of a year, at least 4 digits, with
- for years BCE.Examples:
y A two digit representation of a yearExamples:
a Lowercase Ante meridiem and Post meridiem
A Uppercase Ante meridiem and Post meridiem
B Swatch Internet time
g 12-hour format of an hour without leading zeros
G 24-hour format of an hour without leading zeros
23h12-hour format of an hour with leading zeros
H 24-hour format of an hour with leading zeros
i Minutes with leading zeros
s Seconds with leading zeros
u Microseconds. Note that date() will always generate
000000 since it takes an int parameter, whereas DateTime::format() does support microseconds if DateTime was created with microseconds.Example:
v Milliseconds. Same note applies as for
e Timezone identifierExamples:
I (capital i)Whether or not the date is in daylight saving time
1 if Daylight Saving Time,
ODifference to Greenwich time (GMT) without colon between hours and minutesExample:
P Difference to Greenwich time (GMT) with colon between hours and minutesExample:
p The same as
P, but returns
Z instead of
+00:00 (available as of PHP 8.0.0)Examples:
T Timezone abbreviation, if known; otherwise the GMT offset.Examples:
Z Timezone offset in seconds. The offset for timezones west of UTC is always negative, and for those east of UTC is always positive.
c ISO 8601 date2004-02-12T15:19:21+00:00
U Seconds since the Unix Epoch (January 1 1970 00:00:00 GMT)See also time()
To print out the current date, in the following format,
November 19, 2022, you’ll need to use the formatter string:
F d, Y. If instead you wanted
11/19/22, you’ll need to format your formatter string like this:
echo date("F d, Y"); // November 19, 2022 echo "<br>"; echo date("m/d/y"); // 11/19/22 echo "<br>";
You can use your imagination and do whatever you’d like with the formats.
This is an interesting function since it converts human-readable date strings into Unix timestamps. The
date() function has a second argument. That is the unix timestamp. If you don’t place anything there, it’ll use the
time() function to get the current unix timestamp as the default. But, you can place another value and format it.
Let’s say that you have the following string:
October 10 2022 5:00am. Do you think this will work when we try to convert it to a unix timestamp?
human_readable_datetime = "October 10 2022 5:00am"; $unix_timestamp = strtotime($human_readable_datetime); var_dump($unix_timestamp);
/app/94 DateTime/index.php:21:int 1665374400
Well we get a numeric timestamp, but is it correct? Let’s check with our date time format.
$human_readable_datetime = "October 10 2022 5:00am"; $unix_timestamp = strtotime($human_readable_datetime); echo date("F d, Y | g:ia", $unix_timestamp);
October 10, 2022 | 5:00am
We get the same information, but formatted differently because of our formatter string:
F d, Y | g:ia.
Pretty cool. You can then ask users to submit a date and time and not ask for a particular format. The
strtotime() function will convert it to unix and then you can format it however you’d like with the
If you want to be super specific how you create your unix timestamp, you can use the
mktime() function instead of the
strtotime() function. This contains a list of arguments that are in a specific order.
mktime( int $hour, ?int $minute = null, ?int $second = null, ?int $month = null, ?int $day = null, ?int $year = null ): int|false
These are all numeric values with common constraints. For example, the
second must be between
year can be 2 or 4 digits. The current valid range for the year is between
If we wanted to create
October 10 2022 5:00am, we would need to do the following:
$made_time = mktime(5, 00, 00, 10, 10, 2022); echo date("F d, Y | g:ia", $made_time); echo "<br>";
October 10, 2022 | 5:00am
The last function that we’ll cover is the
checkdate() function. The
checkdate() function accepts 3 arguments:
year. If the date is correct, it’ll return
var_dump( checkdate(11, 20, 2023) ); var_dump( checkdate(13, 20, 2023) ); var_dump( checkdate(02, 29, 2023) ); // great way to check for leap-year var_dump( checkdate(02, 29, 2024) ); // great way to check for leap-year
/app/94 DateTime/index.php:28:boolean true /app/94 DateTime/index.php:29:boolean false /app/94 DateTime/index.php:30:boolean false /app/94 DateTime/index.php:31:boolean true
As you can see, 2023 isn’t a leap-year, but 2024 is. See you in the next article when we look at the