PHP Date and Time

📘 PHP 👁 24 views 📅 Dec 22, 2025
⏱ Estimated reading time: 2 min

What is Date and Time in PHP?

PHP provides powerful built-in functions to get, format, and manipulate date and time. These functions are widely used in logging systems, user activities, scheduling, and dynamic websites.


Setting the Default Timezone

Always set the correct timezone before working with date and time.

date_default_timezone_set("Asia/Kolkata");

Getting Current Date and Time

The date() function is used to format the current date and time.

echo date("Y-m-d"); // 2025-01-01 echo date("H:i:s"); // 14:30:45 echo date("Y-m-d H:i:s");

Common Date Format Characters

CharacterDescriptionExample
Y4-digit year2025
y2-digit year25
mMonth (01-12)07
dDay (01-31)21
HHour (24-hour)18
hHour (12-hour)06
iMinutes30
sSeconds45
AAM / PMPM

Using time() Function

Returns the current timestamp (seconds since Jan 1, 1970).

echo time();

Creating Custom Dates – strtotime()

Convert a date string into a timestamp.

echo date("Y-m-d", strtotime("next Monday")); echo date("Y-m-d", strtotime("+7 days"));

Date Difference in PHP

Using DateTime and DateInterval.

$date1 = new DateTime("2025-01-01"); $date2 = new DateTime("2025-01-10"); $diff = $date1->diff($date2); echo $diff->days . " days";

DateTime Class Example

$date = new DateTime(); $date->modify("+1 month"); echo $date->format("Y-m-d");

Check Valid Date

if (checkdate(2, 29, 2024)) { echo "Valid Date"; } else { echo "Invalid Date"; }

Display Day Name

echo date("l"); // Monday

Formatting Date from Database

$dbDate = "2025-07-21"; echo date("d-m-Y", strtotime($dbDate));

Common Use Cases

  • Showing current date/time

  • User activity logs

  • Expiry dates

  • Countdown timers

  • Event scheduling


Best Practices

  • Always set timezone

  • Use DateTime class for complex operations

  • Store dates in Y-m-d H:i:s format in database

  • Convert dates only when displaying


Conclusion

PHP date and time functions make it easy to manage and manipulate time-based data. Mastering these functions is essential for building dynamic and time-aware web applications.



🔒 Some advanced sections are available for Registered Members
Register Now

Share this Post


← Back to Tutorials

Popular Competitive Exam Quizzes