PHP Functions 5 programs with output 15 Q/A 5 MCQs

Learning Objectives – after this chapter you will be able to:

  • Format dates and times with date() and its format characters.
  • Create and check timestamps with time(), mktime(), strtotime() and checkdate().
  • Calculate with dates using the DateTime classes.
  • Use the calendar functions for days in a month, Julian Day Counts and Easter.
  • Know which date functions are deprecated in PHP 8.1.
Timestamps and Time Zones

PHP measures time as a Unix timestamp – the number of seconds since 1 January 1970 00:00:00 GMT (the Unix Epoch). Functions such as time() return a timestamp; date() turns a timestamp into readable text.

Every date function uses the default time zone, set by date.timezone in php.ini (XAMPP default: Europe/Berlin) or at run time with date_default_timezone_set(). For India use Asia/Kolkata. The outputs in this chapter were produced on the date the book was built, so your output will show your current date.

Date and Time Functions
FunctionPurpose
checkdate(month, day, year)Validates a date; returns true or false.
date(format [, timestamp])Formats the local date/time according to the format string.
gmdate(format [, timestamp])Like date() but in GMT/UTC.
idate(format [, timestamp])Formats one part of a date as an integer.
getdate([timestamp])Returns an associative array of date/time parts.
localtime([timestamp, associative])Returns the local time as an array.
gettimeofday([as_float])Returns the current time as an array (sec, usec, minuteswest, dsttime).
time()Returns the current Unix timestamp.
microtime([as_float])Returns the current timestamp with microseconds.
mktime(hour, minute, second, month, day, year)Returns the Unix timestamp of a date (missing arguments = current values).
gmmktime(...)Like mktime() for a GMT date.
strtotime(text [, base])Parses an English date/time description into a timestamp ("next Monday", "+1 week").
date_default_timezone_set(tz) / date_default_timezone_get()Sets / gets the default time zone.
strftime(format [, timestamp]) / gmstrftime()Formatted local/GMT date according to the locale – deprecated since PHP 8.1; use date() or IntlDateFormatter.
date() Format Characters
CharMeaningExample values
dDay of the month, 2 digits with leading zero01 to 31
jDay of the month without leading zero1 to 31
DDay of the week, three lettersMon to Sun
l(lowercase L) Full day of the weekSunday to Saturday
NISO-8601 day of the week1 (Monday) to 7 (Sunday)
wNumeric day of the week0 (Sunday) to 6 (Saturday)
SEnglish ordinal suffix for the dayst, nd, rd, th
zDay of the year, starting from 00 to 365
WISO-8601 week number of the year (weeks start on Monday)1 to 53
FFull month nameJanuary to December
MMonth, three lettersJan to Dec
mMonth with leading zero01 to 12
nMonth without leading zero1 to 12
tNumber of days in the month28 to 31
LLeap year?1 if leap year, 0 otherwise
YYear, 4 digits2026
yYear, 2 digits26
aLowercase ante/post meridiemam, pm
AUppercase ante/post meridiemAM, PM
BSwatch Internet time000 to 999
gHour, 12-hour format, no leading zero1 to 12
GHour, 24-hour format, no leading zero0 to 23
hHour, 12-hour format, leading zero01 to 12
HHour, 24-hour format, leading zero00 to 23
iMinutes with leading zero00 to 59
sSeconds with leading zero00 to 59
I(capital i) Daylight saving time?1 if DST, 0 otherwise
ODifference to GMT in hours+0530
PDifference to GMT with colon+05:30
TTime zone abbreviationIST, EST …
ZTime zone offset in seconds (west of UTC negative)-43200 to 50400
cISO-8601 date2026-10-22T15:19:21+05:30
rRFC 2822 formatted dateThu, 22 Oct 2026 15:19:21 +0530
USeconds since the Unix Epoch1792662561
File: htdocs/phpbook/ch24/dateformat.php
<?php
date_default_timezone_set("Asia/Kolkata");
echo "d-m-Y        : " . date("d-m-Y") . "<br>";
echo "D, jS F Y    : " . date("D, jS F Y") . "<br>";
echo "l            : " . date("l") . "<br>";
echo "h:i:s A      : " . date("h:i:s A") . "<br>";
echo "H:i (24 hr)  : " . date("H:i") . "<br>";
echo "Day of year z: " . date("z") . ", week W: " . date("W") . "<br>";
echo "Days in month: " . date("t") . ", leap year: " . (date("L") ? "yes" : "no") . "<br>";
echo "Time zone    : " . date("T P e") . "<br>";
echo "ISO 8601 (c) : " . date("c") . "<br>";
echo "RFC 2822 (r) : " . date("r") . "<br>";
echo "Escaped text : " . date("\T\o\d\a\y \i\s l");
?>
OUTPUT browser · http://localhost/phpbook/ch24/dateformat.php
d-m-Y : 22-10-2026
D, jS F Y : Thu, 22nd October 2026
l : Thursday
h:i:s A : 12:16:59 PM
H:i (24 hr) : 12:16
Day of year z: 294, week W: 43
Days in month: 31, leap year: no
Time zone : IST +05:30 Asia/Kolkata
ISO 8601 (c) : 2026-10-22T12:16:59+05:30
RFC 2822 (r) : Thu, 22 Oct 2026 12:16:59 +0530
Escaped text : Today is Thursday

A backslash before a character prints it literally (\T\o\d\a\y), because otherwise every letter in the format string has a meaning.

Creating and Checking Dates
File: htdocs/phpbook/ch24/mktime.php
<?php
date_default_timezone_set("Asia/Kolkata");
$ts = mktime(0, 0, 0, 8, 15, 1947);
echo "15 Aug 1947 was a " . date("l", $ts) . "<br>";
echo "Timestamp now: " . time() . "<br>";
echo "checkdate(2, 29, 2028): " . (checkdate(2, 29, 2028) ? "valid" : "invalid") . "<br>";
echo "checkdate(2, 29, 2027): " . (checkdate(2, 29, 2027) ? "valid" : "invalid") . "<br>";
$d = getdate(mktime(10, 30, 0, 1, 26, 2027));
echo "getdate: {$d['weekday']}, {$d['mday']} {$d['month']} {$d['year']} {$d['hours']}:{$d['minutes']}<br>";
echo "idate('Y'): " . idate('Y') . "<br>";
echo "gmdate('H:i') (UTC): " . gmdate("H:i") . ", local: " . date("H:i");
?>
OUTPUT browser · http://localhost/phpbook/ch24/mktime.php
15 Aug 1947 was a Friday
Timestamp now: 1792651620
checkdate(2, 29, 2028): valid
checkdate(2, 29, 2027): invalid
getdate: Tuesday, 26 January 2027 10:30
idate('Y'): 2026
gmdate('H:i') (UTC): 06:47, local: 12:17
strtotime() – dates in plain English
File: htdocs/phpbook/ch24/strtotime.php
<?php
date_default_timezone_set("Asia/Kolkata");
$base = mktime(0, 0, 0, 10, 22, 2026);        // a fixed base date: 22 Oct 2026
foreach (["tomorrow", "+1 week", "next monday", "last day of this month",
          "+3 months 2 days", "first sunday of november 2026"] as $text) {
    echo str_pad($text, 30) . " → " . date("D d-m-Y", strtotime($text, $base)) . "<br>";
}
echo "strtotime('2026-12-25 10:00') = " . strtotime("2026-12-25 10:00");
?>
OUTPUT browser · http://localhost/phpbook/ch24/strtotime.php
tomorrow → Fri 23-10-2026
+1 week → Thu 29-10-2026
next monday → Mon 26-10-2026
last day of this month → Sat 31-10-2026
+3 months 2 days → Sun 24-01-2027
first sunday of november 2026 → Sun 01-11-2026
strtotime('2026-12-25 10:00') = 1798173000
Date Calculations with DateTime

The object-oriented DateTime classes (PHP 5.2+) make calculations easy and handle months and leap years correctly.

File: htdocs/phpbook/ch24/datetime.php
<?php
date_default_timezone_set("Asia/Kolkata");
$dob = new DateTime("2001-05-14");
$today = new DateTime("2026-10-22");
$age = $dob->diff($today);
echo "Age: {$age->y} years, {$age->m} months, {$age->d} days<br>";
echo "Total days: " . $age->days . "<br>";

$due = new DateTime("2026-10-22");
$due->modify("+45 days");
echo "Fee due on: " . $due->format("d M Y (l)") . "<br>";

$interval = new DateInterval("P1M");         // period of 1 month
$period = new DatePeriod(new DateTime("2026-01-10"), $interval, 3);
foreach ($period as $p) {
    echo "Installment: " . $p->format("d-m-Y") . "<br>";
}
$ny = new DateTime("2026-10-22 10:00", new DateTimeZone("Asia/Kolkata"));
$ny->setTimezone(new DateTimeZone("America/New_York"));
echo "10:00 in Bhopal is " . $ny->format("H:i T") . " in New York";
?>
OUTPUT browser · http://localhost/phpbook/ch24/datetime.php
Age: 25 years, 5 months, 8 days
Total days: 9292
Fee due on: 06 Dec 2026 (Sunday)
Installment: 10-01-2026
Installment: 10-02-2026
Installment: 10-03-2026
Installment: 10-04-2026
10:00 in Bhopal is 00:30 EDT in New York
Calendar Functions

The calendar extension (enabled in XAMPP) converts between calendar systems using the Julian Day Count – the number of days since 1 January 4713 BC.

FunctionPurpose
cal_days_in_month(calendar, month, year)Returns the number of days in a month of the given calendar (CAL_GREGORIAN …).
cal_from_jd(julian_day, calendar)Converts a Julian Day Count into a date of the specified calendar (array).
cal_info([calendar])Returns information about a calendar.
cal_to_jd(calendar, month, day, year)Converts a date of a calendar into a Julian Day Count.
easter_date([year])Unix timestamp for midnight on Easter of the given year.
easter_days([year])Number of days after 21 March on which Easter falls.
gregoriantojd(month, day, year) / jdtogregorian(jd)Gregorian date ↔ Julian Day Count.
juliantojd(month, day, year) / jdtojulian(jd)Julian calendar date ↔ Julian Day Count.
jewishtojd(month, day, year) / jdtojewish(jd)Jewish calendar date ↔ Julian Day Count.
frenchtojd(month, day, year) / jdtofrench(jd)French Republican calendar ↔ Julian Day Count.
jddayofweek(jd [, mode])Day of the week of a Julian Day Count (mode 0 number, 1 name, 2 abbreviation).
jdmonthname(jd, mode)Month name of a Julian Day Count.
unixtojd([timestamp]) / jdtounix(jd)Unix timestamp ↔ Julian Day Count.
File: htdocs/phpbook/ch24/calendar.php
<?php
date_default_timezone_set("Asia/Kolkata");
echo "Days in Feb 2028: " . cal_days_in_month(CAL_GREGORIAN, 2, 2028) . "<br>";
$jd = gregoriantojd(10, 22, 2026);
echo "Julian Day Count of 22-10-2026: $jd<br>";
echo "Day of week: " . jddayofweek($jd, 1) . ", month: " . jdmonthname($jd, 1) . "<br>";
echo "Back to Gregorian: " . jdtogregorian($jd) . "<br>";
echo "Same day in the Julian calendar: " . jdtojulian($jd) . "<br>";
echo "Easter 2027: " . date("d M Y", easter_date(2027)) . " (" . easter_days(2027) . " days after 21 March)<br>";
$info = cal_from_jd($jd, CAL_GREGORIAN);
echo "cal_from_jd: {$info['dayname']}, {$info['day']} {$info['monthname']} {$info['year']}";
?>
OUTPUT browser · http://localhost/phpbook/ch24/calendar.php
Days in Feb 2028: 29
Julian Day Count of 22-10-2026: 2461336
Day of week: Thursday, month: October
Back to Gregorian: 10/22/2026
Same day in the Julian calendar: 10/9/2026
Easter 2027: 28 Mar 2027 (7 days after 21 March)
cal_from_jd: Thursday, 22 October 2026
Key Takeaways
  • A Unix timestamp counts seconds since 1 January 1970 GMT; time() returns the current one.
  • date(format, timestamp) formats dates: d m Y, D l, h H i s A, F M, t L, c r U …
  • Set the time zone with date.timezone or date_default_timezone_set("Asia/Kolkata").
  • mktime() builds a timestamp; checkdate() validates a date; strtotime() understands English text.
  • DateTime, DateInterval and DatePeriod simplify date arithmetic and time-zone conversion.
  • Calendar functions convert through the Julian Day Count; strftime() is deprecated since PHP 8.1.
Program File

Extract the ZIP into C:\xampp\htdocs. It creates the folder phpbook/ch24 used in the file labels above; open the programs at http://localhost/phpbook/… with Apache (and MySQL, where needed) started in the XAMPP Control Panel.

Question / Answer (15 questions)

Answer : The number of seconds that have elapsed since 1 January 1970 00:00:00 GMT (the Unix Epoch). time() returns the current timestamp.

Answer : In php.ini set date.timezone = Asia/Kolkata, or call date_default_timezone_set("Asia/Kolkata") at the start of the script.

Answer : date(format [, timestamp]) – it returns the timestamp (default: now) formatted according to the format string.

Answer : date("d-m-Y h:i A").

Answer : d is the day with a leading zero (01–31), j without (1–31). h is the 12-hour hour with a leading zero (01–12), H the 24-hour hour with a leading zero (00–23).

Answer : l (lowercase L) gives the full day name, e.g. Thursday; F gives the full month name, e.g. October.

Answer : Escape it with a backslash, e.g. date("\T\o\d\a\y \i\s l").

Answer : It returns the Unix timestamp for the given hour, minute, second, month, day and year; omitted arguments take the current values.

Answer : checkdate(2, 29, 2027) – it returns false because 2027 is not a leap year.

Answer : It converts an English date/time description into a timestamp, e.g. strtotime("next monday") or strtotime("+1 week", $base).

Answer : Create two DateTime objects and call $d1->diff($d2); the returned DateInterval has y, m, d and days properties.

Answer : $d = new DateTime("2026-10-22"); $d->modify("+45 days"); or $d->add(new DateInterval("P45D"));

Answer : A continuous count of days since 1 January 4713 BC, used by the calendar functions to convert between Gregorian, Julian, Jewish and French Republican dates.

Answer : cal_days_in_month(CAL_GREGORIAN, $month, $year), or date("t", $timestamp).

Answer : strftime() and gmstrftime(). Use date()/DateTime::format() or the IntlDateFormatter class for locale-aware formatting.
MCQ Test : Check Your Understanding (5 questions)

Select an option and press Check Answer, or answer all questions and press Submit Test to see your score. Each answer comes with an explanation.

Q1. Which format character prints the full name of the day?

Show Answer

Correct Answer : C. l
Lowercase L gives Sunday … Saturday.

Q2. date("H") returns the hour in:

Show Answer

Correct Answer : B. 24-hour format with leading zero
H is 00–23.

Q3. Which function validates a date?

Show Answer

Correct Answer : B. checkdate()
checkdate(month, day, year) returns true or false.

Q4. The Unix Epoch is:

Show Answer

Correct Answer : B. 1 January 1970 GMT
Timestamps count seconds from 1 January 1970.

Q5. Which function is deprecated since PHP 8.1?

Show Answer

Correct Answer : C. strftime()
strftime() and gmstrftime() are deprecated.

Bibliography/References

The notes on this page are the author’s own compilation from the e-book PHP: Basics to Advance. Every program was run on Apache with PHP 8 and MariaDB, and the output shown is the real result of that run. The works listed below were consulted and are cited for attribution and further reading. Product names and trademarks belong to their respective owners.

  1. The PHP Group. (n.d.). PHP Manual – date. https://www.php.net/manual/en/function.date.php
  2. The PHP Group. (n.d.). PHP Manual – Date/Time Functions. https://www.php.net/manual/en/ref.datetime.php
  3. The PHP Group. (n.d.). PHP Manual – The DateTime class. https://www.php.net/manual/en/class.datetime.php
  4. The PHP Group. (n.d.). PHP Manual – Calendar Functions. https://www.php.net/manual/en/ref.calendar.php
  5. The PHP Group. (n.d.). PHP Manual – List of Supported Timezones (Asia). https://www.php.net/manual/en/timezones.asia.php