PHP Date and Time Tutorial: Formatting, Timezones, and Practical Examples

Last updated 3 months, 4 weeks ago | 288 views 75     5

Tags:- PHP

Introduction: Why PHP Date and Time Handling Matters

Time is a core part of every application—whether you're logging user activity, processing orders, scheduling posts, or displaying timestamps. Handling date and time in PHP is both common and critical, but it can get tricky if you rely only on the basic date() function.

With PHP's powerful built-in functions and classes like DateTime, you can format, manipulate, and compare dates with precision. This guide walks you through the most important date/time features in PHP, from beginner to advanced, with working code examples.


PHP Date and Time Basics

date() Function

The date() function returns the current date and/or time in the format you specify.

echo date('Y-m-d'); // Output: 2025-06-17
echo date('H:i:s'); // Output: 14:30:05 (current time)

Common format characters:

Format Meaning Example
Y 4-digit year 2025
m 2-digit month 06
d Day of the month 17
H Hour (24-hour format) 14
i Minutes 30
s Seconds 05

Working with time() and strtotime()

time() - Current Unix Timestamp

echo time(); // Output: 1749787805 (Unix timestamp)

strtotime() - Convert English text to timestamp

$nextWeek = strtotime('+1 week');
echo date('Y-m-d', $nextWeek); // Output: 2025-06-24

Useful strings:

  • 'next Monday'

  • '+2 days'

  • 'last Friday'


The Power of DateTime Class

✅ Creating DateTime Objects

$date = new DateTime(); // Current date/time
$specificDate = new DateTime('2025-01-01 08:00:00');

✅ Formatting with format()

echo $date->format('Y-m-d H:i:s'); // Output: 2025-06-17 14:30:05

✅ Timezone Control with DateTimeZone

$tz = new DateTimeZone('Asia/Kolkata');
$date->setTimezone($tz);
echo $date->format('Y-m-d H:i:s'); // Adjusted for timezone

⏳ PHP Date Calculations

✅ Adding and Subtracting Dates

$date = new DateTime('2025-01-01');
$date->add(new DateInterval('P1M')); // Add 1 month
echo $date->format('Y-m-d'); // Output: 2025-02-01
$date->sub(new DateInterval('P10D')); // Subtract 10 days
echo $date->format('Y-m-d'); // Output: 2025-01-22

Interval Format Legend:

Code Meaning
P Period
Y Years
M Months
D Days
T Time
H Hours
I Minutes
S Seconds

Comparing Dates

$d1 = new DateTime('2025-06-01');
$d2 = new DateTime('2025-06-17');

if ($d1 < $d2) {
    echo "d1 is earlier than d2";
}

✅ Calculating the Difference

$interval = $d1->diff($d2);
echo $interval->format('%R%a days'); // Output: +16 days

Full Example: Date Summary Tool

<?php
// Create a date and timezone
$date = new DateTime('2025-06-17 10:00:00', new DateTimeZone('UTC'));

// Clone it for manipulation
$modifiedDate = clone $date;
$modifiedDate->add(new DateInterval('P1M10D')); // Add 1 month and 10 days

// Calculate difference
$diff = $date->diff($modifiedDate);

echo "Original Date: " . $date->format('Y-m-d H:i:s') . "\n";
echo "Modified Date: " . $modifiedDate->format('Y-m-d H:i:s') . "\n";
echo "Difference: " . $diff->format('%m months, %d days') . "\n";
?>

Output:

Original Date: 2025-06-17 10:00:00
Modified Date: 2025-07-27 10:00:00
Difference: 1 months, 10 days

⚠️ Tips & Common Pitfalls

✅ Tips

  • Use DateTime for anything beyond display—it’s more powerful and reliable.

  • Always specify timezones to avoid inconsistencies.

  • Use clone before modifying a DateTime to preserve original values.

  • Format using format() rather than date() when using DateTime.

❌ Common Mistakes

  • Forgetting to account for timezones in server environments.

  • Using '+' . $days . ' days' in strtotime() instead of using DateInterval.

  • Misusing format characters (m for month, not minutes).


Quick Comparison Table

Feature date() & time() DateTime
Easy Formatting
Timezone Handling
Date Calculations ✅ (with DateInterval)
Comparison Support
OOP Support

 

Advanced PHP Date and Time Techniques

Handling Recurring Events

For events like weekly meetings or monthly billings, you can use loops with DateInterval and DatePeriod.

$start = new DateTime('2025-07-01');
$end = new DateTime('2025-09-01');
$interval = new DateInterval('P1W'); // 1 week

$period = new DatePeriod($start, $interval, $end);

foreach ($period as $date) {
    echo $date->format('Y-m-d') . "\n";
}

Output:

2025-07-01  
2025-07-08  
...  
2025-08-26  

Localizing Dates (IntlDateFormatter)

To display dates in different languages or regions, use PHP's IntlDateFormatter class.

$fmt = new IntlDateFormatter(
    'fr_FR', // Locale
    IntlDateFormatter::LONG,
    IntlDateFormatter::NONE
);

$date = new DateTime('2025-06-17');
echo $fmt->format($date); // Output: 17 juin 2025

Validating User Input Dates

When users input custom date formats (e.g., dd-mm-yyyy), use DateTime::createFromFormat():

$input = '17-06-2025';
$date = DateTime::createFromFormat('d-m-Y', $input);

if ($date && $date->format('d-m-Y') === $input) {
    echo "Valid date!";
} else {
    echo "Invalid format.";
}

Storing Dates in Databases (Best Practice)

  • Always store dates in UTC in the database.

  • Convert to user timezone on display only.

$utcDate = new DateTime('now', new DateTimeZone('UTC'));
echo $utcDate->format('Y-m-d H:i:s'); // Store this in DB

// Convert to user timezone
$utcDate->setTimezone(new DateTimeZone('Asia/Kolkata'));
echo $utcDate->format('Y-m-d H:i:s'); // Show user

Converting Between Formats

You can convert any date format easily:

$input = '06/17/2025';
$date = DateTime::createFromFormat('m/d/Y', $input);
echo $date->format('Y-m-d'); // Output: 2025-06-17

Advanced Tips Recap

Scenario Tool/Technique
Recurring events DatePeriod + DateInterval
Localized display IntlDateFormatter
User input validation DateTime::createFromFormat()
Timezone-safe storage/display Use UTC + convert on output
Flexible date conversions CreateFromFormat + format chaining

 

✅ Conclusion: Best Practices for PHP Date/Time

PHP date and time handling can be simple or sophisticated—depending on your needs. For static formatting, date() is fine. But for anything dynamic like calculating due dates, adjusting timezones, or scheduling tasks, go with DateTime and DateInterval.

Key Takeaways:

  • Prefer DateTime over date() for flexibility.

  • Always manage timezones consciously.

  • Use DateInterval for clean, readable calculations.

  • Validate user input dates using DateTime::createFromFormat.