Baking Brad

Mastering PHP Dates and Time: A Comprehensive Guide with Real Code Examples

January 8, 2024

Mastering PHP Dates and Time: A Comprehensive Guide with Real Code Examples

1. Introduction to Date and Time in PHP

Overview of built-in date/time capabilities

PHP has extensive built-in support for working with dates and times. Some of the key capabilities include:

  • Getting the current date and time
  • Formatting dates and times
  • Performing date calculations and manipulations
  • Converting between different date formats and timestamps
  • Working with timezones
  • Validating and parsing user-provided dates/times
  • Date localization support

Date and time functionality is provided through a combination of PHP's built-in date/time functions as well as the DateTime and DateInterval classes.

Why date/time features are useful

Handling dates and times is crucial for most web applications. For example:

  • Displaying the date on web pages
  • Performing age verification and restrict access based on birthdate
  • Scheduling future posts/events and alerts
  • Analyzing site traffic by date/time
  • Setting deadlines, countdowns, elapsed time
  • Recording the date/time data was added or changed

By leveraging PHP's robust date and time capabilities, developers can easily incorporate useful features that deal with dates and times into their applications.

In this comprehensive guide, we will explore the many date/time tools available in PHP through lots of concrete code examples.

2. Working with Timestamps

What is a timestamp

A timestamp is a numeric value representing a specific date and time. In PHP, timestamps are returned as integer values indicating the number of seconds since the Unix Epoch (January 1, 1970 00:00:00 GMT).

Getting the current timestamp with time()

The time() function returns the current timestamp:

 $now = time(); // e.g. 1674691935 

Converting timestamps to readable dates

Timestamps can be converted into human-readable dates using the date() function:

 echo date("M j, Y g:ia", $now); // e.g. Jan 25, 2023 1:12pm 

Creating timestamps from dates/times

The strtotime() function creates timestamps from human-readable dates:

 $timestamp = strtotime("July 4, 2025"); 

Useful timestamp functions and examples

// Current timestamp
time();

// Timestamp for tomorrow
strtotime("+1 day");

// Timestamp for 3 days ago
strtotime("-3 days"); 

// Timestamp exactly one month from now 
strtotime("+1 month"); 

Some examples showing conversion between timestamps and readable dates:

$ts = 1674691935; 
echo "Timestamp: $ts";
echo date("M j, Y", $ts); // Jan 25, 2023
 
$date = "March 30, 2025"; 
$ts = strtotime($date); 
echo $date . " is timestamp: " . $ts;

3. Formatting Dates and Times

Using the date() function

The date() function is used to format a date/time into a more human-readable string. It accepts two arguments:

date(format, timestamp); 

The timestamp is optional and defaults to the current time if omitted.

Available formatting options

Some commonly used formatting options include:

  • F - Full month name (March)
  • M - Short month name (Mar)
  • d - Day with leading 0's (05)
  • l - Full day name (Sunday)
  • D - Short day name (Sun)
  • Y - 4-digit year (2025)
  • y - 2-digit year (25)
  • h - 12-hour format hour
  • H - 24-hour format hour
  • i - Minutes with leading 0's
  • s - Seconds with leading 0's

Examples of common formats

// March 12, 2025 at 3:30pm 
echo date("F j, Y g:ia"); 

// 03-12-2025 
echo date("m-d-Y"); 

// Wed Mar 02 2025 
echo date("D M d Y");

Localization and timezones

The setlocale() function can be used to output dates in other languages based on locale. Timezones can also be set to display dates/times appropriately for different geographic regions.

setlocale(LC_TIME, "fr_FR"); 
echo strftime("Published on %A, %B %d, %Y"); 

date_default_timezone_set('America/New_York'); 
echo date("M j, Y g:ia") . ' EST';

4. Date and Time Arithmetic

Adding/subtracting dates

The DateTime class allows easy date arithmetic:

$date = new DateTime('2025-12-31'); 

// Add 5 days 
$date->add(new DateInterval('P5D')); 

// Subtract 3 months 
$date->sub(new DateInterval('P3M'));

Diffing dates

The DateInterval class represents the difference between dates:

$start = new DateTime('2023-05-15'); 
$end = new DateTime('2023-07-23'); 
$diff = $start->diff($end); // DateInterval object 
echo $diff->format('%m months, %d days'); // 2 months, 8 days 

Useful examples

// Date 2 weeks from today 
$date = new DateTime('+2 weeks'); 

// Get days until New Year's Eve 
$nye = new DateTime('12/31/2025'); 
$today = new DateTime(); 
$diff = $nye->diff($today); 
echo $diff->days . " days until NYE!"; 

5. Working with Date and Time Objects

Creating DateTime and DateInterval objects

$datetime = new DateTime(); // Current date/time 
$datetime = new DateTime('2025-10-12'); // Custom date 
$interval = new DateInterval('P2Y4DT16H'); // 2 years, 4 days, 16 hours
 

Useful methods and examples

$datetime->setDate(2025, 5, 12); 
$datetime->setTime(15, 30, 00); 
$datetime->add($interval); 
$datetime->sub($interval); 
$datetime->format('Y-m-d H:i:s'); 

Setting timezones

Dates can be converted between timezones:
$datetime = new DateTime(); 
$datetime->setTimezone(new DateTimeZone('Pacific/Fiji')); 
echo $datetime->format('Y-m-d H:i (T)'); 

6. Handling Date Input

Validating user-entered dates

$userDate = $_POST['date']; 
if (strtotime($userDate) === false) { 
	echo 'Invalid date'; 
	} else { 
	// Valid date 
	} 
	
// Or with DateTime: 
try { $datetime = new DateTime($userDate); // valid date } 
catch(Exception $e) { echo 'Invalid date'; } 

Parsing dates from strings

$string = 'March 12, 2025'; 
$timestamp = strtotime($string); 
echo date('Y-m-d', $timestamp); // 2025-03-12 

// Or with createFromFormat(): 
$datetime = DateTime::createFromFormat('F j, Y', $string); 
echo $datetime->format('Y-m-d'); 

Useful functions and examples

// Validate specific format 
$valid = (bool)DateTime::createFromFormat('m/d/Y', $userDate); 

// Check date range 
$min = new DateTime('1/1/2000'); 
$max = new DateTime('1/1/2030'); 
if ($userDate < $min || $userDate > $max) { // Invalid range } 

7. Real-World Examples

Common use cases

// Get age from birthday 
$birthdate = new DateTime('2000-05-24'); 
$today = new DateTime('2023-01-25'); 
$age = $today->diff($birthdate)->y; 

// Show posts from this week only 
$thisWeek = new DateTime('this week'); 
$posts->where('date', '>', $thisWeek); 

// Future events > current date 
$now = new DateTime(); 
$events->where('start_date', '>', $now); 

Complex examples using multiple concepts

// Localized date picker 
$locale = 'fr_CA'; 
setlocale(LC_TIME, $locale); 
echo strftime('%A %d %B %Y'); 

// Friend birthday reminders 
$bdays = [ 'John' => '1982-11-16', 'Sarah' => '1979-04-08' ]; 
$today = date('m-d'); 

// Check if today is someone's bday 
foreach ($bdays as $name => $bday) { 
	if (date('m-d', strtotime($bday)) == $today) { 
		mail($name, 'Happy birthday!'); 
	} 
} 

Ideas to demonstrate robust handling

// Validate user date before parsing 
if (preg_match('/\d{4}-\d{2}-\d{2}/', $date)) { 
	$datetime = new DateTime($date); 
} else { 
	// error 
} 

// Handle DateException on invalid input 
try { $datetime = new DateTime($date); } 
catch (Exception $e) { // error } 

8. Other Useful Date/Time Functions

Helper functions like getdate()

// Get date array 
$date = getdate(); 
echo $date['mday']; 

// Print multiple formats from timestamp 
$ts = time(); 
echo date('m/d/Y', $ts) . PHP_EOL; 
echo date('F jS, Y', $ts); 

Dealing with special cases

// Next weekday if date falls on weekend 
$date = new DateTime('2025-07-04');  // July 4 = Friday 
if ($date->format('N') >= 6) { 
	$date->modify('next monday'); 
} 

// Handle end of month bug 
$invoiceDate = new DateTime('2025-02-29'); // Feb 29 
if ($invoiceDate->format('n') == '3') { 
	$invoiceDate->setDate(2025, 3, 1); // March 1 
} 

9. Common Pitfalls to Avoid

Common mistakes and how to address

// Off-by-one errors with timestamp comparisons 
$ts = strtotime('2022-12-31'); 
if ($ts >= strtotime('2023')) { 
	// Bug! This passes when it shouldn't 
} 

// Always compare full date strings 
if (date('Y-m-d', $ts) >= '2023-01-01') { 
	// Fixed 
}

Issues with localization

// Set locale properly on every page 
setlocale(LC_TIME, 'fr_FR'); 

// Never assume date formats 
if ($date == '01-23-2025') { 
	// Bug! Won't match in some locales 
}

if (date('y-m-d') == '25-01-23') { 
	// Better approach 
} 

Timestamp boundaries

// Block impossible dates 
if ($birthYear < 1900 || $birthYear > 2030) { 
	// Error 
} 

// Unix timestamp range 
$tsMin = ~31557014; 
$tsMax = 32535292000; 
if ($ts < $tsMin || $ts > $tsMax) { 
	// Out of range error 
} 

10. Date and Time Best Practices

Recommendations

// Always validate first 
$datetime = validateDate($userInput); 

// Use helper functions for clarity 
$timestamp = getTimestamp($datetime); 

// Inline examples for complex operations 
$date->modify('+1 month'); 

// Easier to understand 
// Handle invalid user input 
try { $datetime = new DateTime($data); } catch (Exception $e) { // Error handling } 

// Use DateTime over bare timestamps 
$datetime = new DateTime(); 
$datetime->setTimestamp($timestamp); 

// Set default timezone 
date_default_timezone_set('UTC'); 

Tips for robust and maintainable code

// Break into smaller testable units 
function createEvent($data) { 
	$start = parseDate($data['start']); 
	$end = parseDate($data['end']); 
	if (!validRange($start, $end)) { 
		throw new Exception('Invalid range'); 
	} 
	return new Event($data); 
} 

// Reusable helpers 
function parseDate($date) { 
	// parsing logic 
} 

function validRange($start, $end) { 
	// range validation 
}
Tags: PHP Programming, Date and Time Functions, Web Development, Coding Best Practices, Server-Side Scripting, Application Development