← Back to Chapters

PHP Getdate, Localtime & Gettimeofday

⏰ PHP Getdate, Localtime & Gettimeofday

? Quick Overview

The getdate(), localtime(), and gettimeofday() functions retrieve current date and time details in PHP, including microsecond precision.

? Key Concepts

  • getdate() returns a detailed associative array.
  • localtime() provides raw local time data.
  • gettimeofday() gives high-precision timestamps.

? Syntax & Theory

  • getdate() → human-readable components
  • localtime(time(), true) → low-level array
  • gettimeofday() → seconds + microseconds

?️ Code Example: getdate()

? View Code Example
// Fetch current date and time as an associative array
<?php
$date_info = getdate();
print_r($date_info);
?>

This outputs year, month, day, weekday, hours, minutes, and seconds.

?️ Code Example: localtime()

? View Code Example
// Retrieve raw local time values using current timestamp
<?php
$local_time = localtime(time(), true);
print_r($local_time);
?>

The array includes seconds, minutes, hours, and date offsets.

?️ Code Example: gettimeofday()

? View Code Example
// Get precise time including microseconds
<?php
$time_info = gettimeofday();
print_r($time_info);
?>

Useful for benchmarking and performance measurements.

? Interactive Visualization

Real-time high-precision clock simulation:

Seconds (gettimeofday) 0
Microseconds (usec) 0
Precision Flow

? Use Cases

  • Logging events
  • Performance timing
  • Date-based logic

✅ Tips & Best Practices

  • Use getdate() for readable output.
  • Use gettimeofday() for precision.
  • Combine with date() for formatting.

? Try It Yourself

  • Display current weekday using getdate().
  • Extract minutes from localtime().
  • Measure execution time using gettimeofday().