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:

<?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--;
}
?>

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.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

BackendPHPdateage-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

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.