Backend Development 3 min read

Calculating Student Age Using PHP Date Functions

This tutorial demonstrates how to use PHP variables and the date() function to automatically compute a student's age based on their birthdate, handling current date retrieval, birthday checks, and adjusting the age calculation accordingly.

php中文网 Courses
php中文网 Courses
php中文网 Courses
Calculating Student Age Using PHP Date Functions

The article begins with a requirement analysis: to display a student's age accurately and quickly, the system should store the student's birth year, month, and day, retrieve the current date, and compute the age.

It then outlines the design thinking, asking how to define variables for student information, how to store birth components, how to obtain the current year/month/day, how to calculate the full years elapsed, and how to determine whether the birthday has passed.

A brief knowledge section introduces PHP's Date/Time functions, especially the date() function, its syntax date(format, timestamp) , and common format characters such as Y , n , and j .

Finally, the implementation code is provided:

<code><?php
// Define variables for student's birth year, month, day
$stu_by = 2001;
$stu_bm = 8;
$stu_bd = 07;
// Get current year, month, day
$cur_y = date('Y'); // 4‑digit year
$cur_m = date('n'); // month without leading zero
$cur_d = date('j'); // day without leading zero
// Calculate age
$age = $cur_y - $stu_by;
// Adjust if birthday not yet occurred this year
if ($cur_m < $stu_bm || ($cur_m == $stu_bm && $cur_d < $stu_bd)) {
    $age--;
}
?></code>

The output shows that on 2 November 2020 the script correctly reports the student's age, demonstrating the handling of different current months (e.g., May vs. October) and the birthday‑passed logic.

backendPHPTutorialDateage-calculation
php中文网 Courses
Written by

php中文网 Courses

php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.