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 DateTime
object.
The easiest way to get into this is with examples. We’ll be tackling the following date and time functions:
getdate()
localtime()
date()
strtotime()
mktime()
checkdate()
getdate()
The getdate() function returns an array with the following values for the local time.
<?php
var_dump(getdate());
/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:
seconds
, minutes
and 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 0
to 365
weekday
is the textual representation of the day of the week, i.e. Saturday
month
is the textual representation of the month, i.e. October
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.
<?php
$current_date_time = getdate();
echo $current_date_time['weekday'];
Saturday
localtime()
The localtime()
returns an array identical to that of the structure returned by the C function call.
- “tm_sec” — represents the seconds, from
0
to59
- “tm_min” — represents the minutes, from
0
to59
- “tm_hour” — represents the hours, from
0
to23
- “tm_mday” — represents the day of the month, from
1
to31
- “tm_mon” — represents the month of the year, from
0
(January) to11
(December) - “tm_year” — represents the years since 1900
- “tm_wday” — represents the day of the week,
0
(Sunday) to6
(Saturday) - “tm_yday” — represents the day of the year, from
0
to365
- “tm_isdst” — Positive if daylight savings time is in effect,
0
if not, negative if unknown.
Unfortunately the keys are not displayed. So you’ll need to know what the index value represents.
<?php
var_dump(localtime());
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.
<?php
$localtime = localtime();
$current_year = $localtime[5] + 1900;
echo $current_year;
2022
date()
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 Mon
through Sun
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 weekSunday
through Saturday
N
ISO 8601 numeric representation of the day of the week1
(for Monday) through 7
(for Sunday)
S
English ordinal suffix for the day of the month, 2 charactersst
, nd
, rd
or th
. Works well with j
w
Numeric representation of the day of the week0
(for Sunday) through 6
(for Saturday)
z
The day of the year (starting from 0)0
through 365
Week——
W
ISO 8601 week number of year, weeks starting on MondayExample: 42
(the 42nd week in the year)
Month——
F
A full textual representation of a month, such as January or MarchJanuary
through December
m
Numeric representation of a month, with leading zeros01
through 12
M
A short textual representation of a month, three lettersJan
through Dec
n
Numeric representation of a month, without leading zeros1
through 12
t
Number of days in the given month28
through 31
Year——
L
Whether it’s a leap year1
if it is a leap year, 0
otherwise.
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: 1999
or 2003
X
An expanded full numeric representation of a year, at least 4 digits, with -
for years BCE, and +
for years CE.Examples: -0055
, +0787
, +1999
, +10191
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 +
.Examples: -0055
, 0787
, 1999
, +10191
Y
A full numeric representation of a year, at least 4 digits, with -
for years BCE.Examples: -0055
, 0787
, 1999
, 2003
, 10191
y
A two digit representation of a yearExamples: 99
or 03
Time——
a
Lowercase Ante meridiem and Post meridiemam
or pm
A
Uppercase Ante meridiem and Post meridiemAM
or PM
B
Swatch Internet time000
through 999
g
12-hour format of an hour without leading zeros1
through 12
G
24-hour format of an hour without leading zeros0
through 23h
12-hour format of an hour with leading zeros01
through 12
H
24-hour format of an hour with leading zeros00
through 23
i
Minutes with leading zeros00
to 59
s
Seconds with leading zeros00
through 59
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: 654321
v
Milliseconds. Same note applies as for u
.Example: 654
Timezone——
e
Timezone identifierExamples: UTC
, GMT
, Atlantic/Azores
I
(capital i)Whether or not the date is in daylight saving time1
if Daylight Saving Time, 0
otherwise.O
Difference to Greenwich time (GMT) without colon between hours and minutesExample: +0200
P
Difference to Greenwich time (GMT) with colon between hours and minutesExample: +02:00
p
The same as P
, but returns Z
instead of +00:00
(available as of PHP 8.0.0)Examples: Z
or +02:00
T
Timezone abbreviation, if known; otherwise the GMT offset.Examples: EST
, MDT
, +05
Z
Timezone offset in seconds. The offset for timezones west of UTC is always negative, and for those east of UTC is always positive.-43200
through 50400
Full Date/Time——
c
ISO 8601 date2004-02-12T15:19:21+00:00
r
» RFC 2822/» RFC 5322 formatted dateExample: Thu, 21 Dec 2000 16:01:07 +0200
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: m/d/y
.
<?php
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.
strtotime()
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.
<?php
$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 date()
function.
mktime()
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 0
and 59
. The year
can be 2 or 4 digits. The current valid range for the year is between 1901
and 2038
.
If we wanted to create October 10 2022 5:00am
, we would need to do the following:
<?php
$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
checkdate()
The last function that we’ll cover is the checkdate()
function. The checkdate()
function accepts 3 arguments: month
, day
, and year
. If the date is correct, it’ll return true
otherwise false
.
<?php
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 DateTime
object.
PRIMARY AND FOREIGN KEYS: THE BACKBONE OF RELATIONAL DATABASES
PHP – P96: MYSQL PRIMARY AND FOREIGN KEYS
Primary keys uniquely identify records in a table. Foreign keys establish relationships between tables. They ensure data integrity and enforce uniqueness.
calculate intervals & perform date arithmetic in PHP
PHP – P97: date and time introduction
PHP offers robust tools for working with dates and times. DateTime objects provide powerful date manipulation capabilities.
THE DATETIME OBJECT IN PHP SIMPLIFIES DATE AND TIME MANIPULATION
How do you add 2 weeks to a current date-time or how many days are between two dates? That’s where the DateTime object shines.